Skip to main content
 首页 » 编程设计

python之选择特定文本

2025年05月04日18unruledboy

假设我在下面的变量中有字符串:

text='lsdkjfkj fksjf aksjdafhIncident 11202asdf jfsaldfuaeia' 

我只想选择文本 Incident 11202 并将其保存到一个变量中。

此外,“事件”后面的数字也会发生变化。

我想知道是否有办法复制其后的任何未知字符。

请您参考如下方法:

您可以为此使用正则表达式。

例如尝试以下正则表达式:

import re 
txt='lsdkjfkj fksjf aksjdafhIncident 11202asdf jfsaldfuaei2a' 
print (re.findall ('Incident.\d*', txt)) 
 
>>>['Incident 11202'] 

什么是正则表达式?

正则表达式(简称regex或regexp)是描述搜索模式的特殊文本字符串

什么是 findAll 函数?

re.findall(pattern, string, flags=0)

Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result unless they touch the beginning of another match.

您可以在 here 中阅读更多内容