【问题标题】:python 3 regex string matching ignore whitespace and string.punctuationpython 3正则表达式字符串匹配忽略空格和string.punctuation
【发布时间】:2019-04-13 20:33:17
【问题描述】:

我是正则表达式的新手,想知道如何对两个字符串进行模式匹配。用例类似于在某些文本中查找某个短语。如果有区别,我正在使用 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 string python-3.x pattern-matching non-alphanumeric


【解决方案1】:

你应该使用这样的东西:

re.search(r'\bsome\W+phrase\b', text)
  • '\W'表示非单词字符

  • '+'表示一次或多次

如果您在变量中有给定的短语,您可以先尝试一下:

some_phrase = some_phrase.replace(r' ', r'\W+')

【讨论】:

  • some_phrase = some_phrase.replace(r' ', r'\W+') 打印 'some\W+phrase'。
  • 最后你把 \b 放在开头和结尾。
  • 这不能解决您的问题吗?请向我解释你遇到了什么问题
  • 哦,我明白你的意思了。执行替换,然后使用该字符串进行搜索。是的,这就是我所需要的。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-31
  • 1970-01-01
  • 1970-01-01
  • 2018-11-23
  • 2014-08-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多