我想要获取匹配前后的单词。我可以使用string.split(' ')
,但由于我已经在使用正则表达式,难道没有仅使用正则表达式的更好方法吗?
使用匹配对象,我可以获取精确位置。然而,这个位置是字符索引。
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
输出:
匹配:12my90 Indix
范围:(9,15)
匹配词前后的单词:12my90
为了获得匹配的单词和之前的单词,我尝试了以下方法:
pattern = re.compile(r"(\b(w+)\b)\s(\b12(\w+)90\b)",re.IGNORECASE |
re.UNICODE)
没有任何匹配结果。
\s
包括换行符。 - Toto