正则表达式关于芬德尔找到两边有空格的子串

2024-09-29 01:20:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着用关于芬德尔在我的文本栏中,找到以下两个两边都有空格的选项,因为这是唯一重要的。我使用以下脚本

url = '#MnA deals for 2015 across all #oilandgas sectors were lower than WAR WARduring the CFO Great CIO Recession' 

regex=re.findall(r'WAR|CIO|CISO|CTO|C-Suite|CMO|CFO|Founder+',url)  
print regex 
['WAR', 'WAR', 'CFO', 'CIO']

而不是这个我只想要

^{pr2}$

从第二次开始,这不仅仅是战争,更是一场战争,我不想那样

还有什么是运算符来得到我想在下标前面看到的所有东西,比如

['WAR', 'WARduring','CFO', 'CIO']

感谢每一个帮助


Tags: 脚本urlfor选项allregexacross空格
3条回答

方法一:错误地将战争视为战争

另一种方法:使用\b仅分隔单词

regex=re.findall(r'\b(WAR|CIO|CISO|CTO|C-Suite|CMO|CFO|Founder)\b',url)


url = '#MnA deals for 2015 across all #oilandgas theWAR sectors were lower than WAR WARduring the CFO Great CIO'

regex=re.findall(r'(WAR|CIO|CISO|CTO|C-Suite|CMO|CFO|Founder+)(?=\s|$)', url)  # bug with start of word
print regex
regex=re.findall(r'\b(WAR|CIO|CISO|CTO|C-Suite|CMO|CFO|Founder)\b',url)
print regex
['WAR', 'WAR', 'CFO', 'CIO']
['WAR', 'CFO', 'CIO']

在正则表达式中使用单词boundary [Know more]将解决您的问题

正则表达式

\b(?:WAR|CIO|CISO|CTO|C-Suite|CMO|CFO|Founder+)\b

代码

^{pr2}$

您可以使用展望:

>>> re.findall(r'\b(?:WAR|CIO|CISO|CTO|C-Suite|CMO|CFO|Founder+)(?=\s|$)', url)
['WAR', 'CFO', 'CIO']

(?=\s|$)将断言关键字后是否存在空格或行尾。在

对于第二个任务,请使用以下正则表达式:

^{pr2}$

这里\w*后的关键字将匹配0个或多个单词字符。在

相关问题 更多 >