正则表达式匹配字符串及其周围的 2 个字符

我想匹配一个特定的单词,然后检索包含它的字符串及其两侧的两个邻居


下面的代码部分实现了这一点。但当匹配词出现在字符串的开头时,它会失败。


那么在正则表达式中是否有更高效、更灵活的方法来实现这一目标呢?


text = "The world is a small place, we should try to take care of it"

sub = r'(\w+|.)\W(\w+|.)\W+(try)\W+(\w+|.)\W'

surrounding_text = re.findall(sub, text)


互换的青春
浏览 148回答 4
4回答

慕的地6264312

只需使用一个简单的列表:text = "The world is a small place, we should try to take care of it"d = text.split()try:    idx = d.index('world')    print("{} {} {}".format(d[idx - 1], d[idx], d[idx + 1]))except ValueError:    print("Not in the text.")哪个产量The world is您需要在这里考虑负指数。

慕的地10843

您可以使用?量词要匹配单词“try”和上一个或下一个单词的一个字符:试试看(. )?try( .)?解释:(. )?:匹配一个字符,然后匹配一个空格零次或一次try: 字面意思是“尝试”( .)?:匹配空格和一个字符零次或一次如果您想匹配单词字符或整个单词,您可以修改.来匹配。试试看\w\w+要匹配两侧最多两个?单词,您可以将 the 替换为{0, 2} 

慕丝7291255

import retext = "The world is a small place, we should try to take care of it"sub = re.compile(r'(?P<all>(\w*)\s*try\s*(\w*))')&nbsp; &nbsp; rez = [m.groupdict() for m in sub.finditer(text)]&nbsp; &nbsp; for item in rez:&nbsp; &nbsp; &nbsp; &nbsp;print(item["all"])&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; text = "try to take care of it"&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; rez = [m.groupdict() for m in sub.finditer(text)]&nbsp; &nbsp; for item in rez:&nbsp; &nbsp; &nbsp; &nbsp;print(item["all"])我测试了它:The world is a small place, we should try to take care of ittry to take care of it并得到:should try totry tohttps://regex101.com/r/DlSJsJ/1

森栏

您可以将组设置为可选并使用锚点:(?:^|(?:(\w+)\W+)?(\w+)\W+)(world)(?:\W+(\w+)|$)正则表达式演示(?:^|(?:(\w+)\W+)?(\w+)\W+):匹配行开始或之后的模式|(?:(\w+)\W+)?(\w+)\W+:匹配一个或两个单词(?:\W+(\w+)|$)匹配 1 个以上非单词字符或字符串末尾之后的单词
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python