我是regex的新手,想知道如何对两个字符串进行模式匹配。用例类似于在某些文本中找到某个短语。如果有区别的话,我使用的是python 3.7。
phrase = "some phrase" #the phrase I'm searching for
可能匹配:
text = "some#@$#phrase"
^^^^ #non-alphanumeric can be treated like a single space
text = "some phrase"
text = "!!!some!!! phrase!!!"
这些不匹配:
text = "some phrases"
^ #the 's' on the end makes it false
text = "ssome phrase"
text = "some other phrase"
我试过使用类似的东西:
re.search(r'b'+phrase+'b', text)
如果您提供了一个有效的解决方案,我将非常感谢您解释为什么regex有效。
您应该使用这样的东西:
re.search(r'bsomeW+phraseb', text)
'\W'表示非文字字符
"+"表示一次或多次
如果你在一个变量中有一个给定的短语,你可以尝试一下:
some_phrase = some_phrase.replace(r' ', r'W+')