Python正则表达式获取匹配周围的单词

2024-04-16 19:53:57 发布

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

我想在比赛前后得到这些词。我可以使用string.split(' ')——但是我已经使用regex了,难道没有更好的方法只使用regex吗

使用匹配对象,我可以得到确切的位置。但是,此位置是字符索引的

import re

myString = "this. is 12my90\nExample string"
pattern = re.compile(r"(\b12(\w+)90\b)",re.IGNORECASE |  re.UNICODE)

m = pattern.search(myString)
print("Hit: "+m.group())
print("Indix range: "+str(m.span()))
print("Words around match: "+myString[m.start()-1:m.end()+1]) # should be +/-1 in _words_, not characters

输出:

Hit: 12my90 Indix

range: (9, 15)

Words around match: 12my90

为了得到匹配的单词和之前的单词,我试着:

pattern = re.compile(r"(\b(w+)\b)\s(\b12(\w+)90\b)",re.IGNORECASE | 
re.UNICODE)

没有匹配结果


Tags: restringunicoderangeregexaroundpatternwords
2条回答

缺少新行字符

regx = r"(\w+)\s12(\w+)90\n(\w+)"

在第二种模式中,您必须像\w+一样转义w+

除此之外,您的示例中还有一个新行,您可以使用下面的另一个\s来匹配它

你的模式与3个捕获组可能看起来像

(\b\w+\b)\s(\b12\w+90\b)\s(\b\w+\b)

Regex demo

您可以使用捕获组来获取值

print("Words around match: " + m.group(1) + " " + m.group(3))

相关问题 更多 >