【问题标题】:re.match returns null although the string appears in the sentence [duplicate]尽管字符串出现在句子中,但 re.match 返回 null [重复]
【发布时间】:2015-09-17 12:31:00
【问题描述】:

我正在尝试将字符串“hello world”与句子匹配。我认为这意味着它会在句子中搜索该字符串并返回一个表示成功的值。

但是当我尝试这段代码时,打印出来的都是“无”。

import re
sentence = "why do we write hello world so often?"
match1 = re.match('hello world', sentence)
print match1

【问题讨论】:

  • 这不是你应该使用正则表达式的地方。使用in
  • if 'hello world' in sentence:。如果你需要更复杂的东西,你应该考虑模糊搜索。

标签: python regex match


【解决方案1】:

match 只查看字符串的开头。

你应该改用search

match1 = re.search('hello world', sentence)

请注意,您不应将正则表达式用于此特定任务。 hello world 是一个非常具体的文本,您可以使用 in 来检查它是否包含在字符串中。当你有 pattern 时应该使用正则表达式。

如果您坚持使用match,您应该将您的正则表达式更改为:

match1 = re.match('.*hello world', sentence)

现在.* 匹配直到hello world 标记之前的所有内容,并且正则表达式“hello world”将匹配您句子中的字符串“hello world”。

【讨论】:

    猜你喜欢
    • 2020-05-28
    • 2019-01-01
    • 2018-03-09
    • 2016-03-22
    • 1970-01-01
    • 1970-01-01
    • 2020-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多