在多个空格后查找单词的正则表达式

2024-09-20 03:41:24 发布

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

我试图在一个文本文件中查找一个接一个单词。我能找到这个单词,如果它后面跟一个空格。那就是

string = 'I love my world of dreams'
print re.findall (r'(?<=my)[^ -.]*', string)

我的输出是

^{pr2}$

但如果“我的”like后面有多个空格或多个空格

string = 'I love my        world of dreams'

这将只返回我“”。我想跳过所有空格,找到下一个单词接一个单词“我的”。在


Tags: ofreworldstringmy单词like空格
3条回答

lookbehind不能有无限长的匹配。您必须在my之后匹配整个内容并提取子组:

my\s*([^ -.]+)

Regular expression visualization

Debuggex Demo

尝试fileinput读取文件中的行。假设文件的每一行都存储在字符串str123中。下面的代码将帮助您。。。在

>>>
>>> str123 = ' This is a very long  space in the text'
>>> pqr123 = str123.split()

>>>
>>> nextword = ''
>>> for i in range(len(pqr123)):
...     nextword = pqr123[i]
...     print ('nextword :'+ nextword + '\n')
...
nextword :This

nextword :is

nextword :a

nextword :very

nextword :long

nextword :space

nextword :in

nextword :the

nextword :text

>>>

字符串“This is a very long space in The text”在longspace之间有2个空格。在

您可以使用\s+(匹配所有whitspaces)或' +',但是由于look-behind需要固定宽度的模式,您需要将其放在look-behind之外并使用分组,您也可以只使用re.search: 公司名称:

>>> string = 'I love my           world of dreams'
>>> print re.search (r'(?<=my)\s+([^ -.]*)', string).group(1)
world

或者

^{pr2}$

相关问题 更多 >