我想在比赛前后获得单词。我可以使用 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
输出:
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)
没有匹配项。
最佳答案
在第二个模式中,你必须像 \w+
这样转义 w+
。
除此之外,您的示例中还有一个换行符,您可以使用以下 \s
具有 3 个捕获组的模式可能看起来像
(\b\w+\b)\s(\b12\w+90\b)\s(\b\w+\b)
您可以使用捕获组来获取值
print("Words around match: " + m.group(1) + " " + m.group(3))
关于Python Regex - 获取匹配词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58246803/