【问题标题】:why the following code does not return match object?为什么下面的代码不返回匹配对象?
【发布时间】:2020-05-29 23:32:39
【问题描述】:
txt = 'is worth 12$'
pattern = re.compile('12$')
match = pattern.search(txt)
if match != None:
    print('ys')
else:
    print('no')

它打印no。我想知道为什么字符串'12$'不匹配。

【问题讨论】:

  • 为什么要使用正则表达式在文本中查找 12$。您可以简单地搜索字符串 12$ 。如果你想找到任何数字后跟 $ 符号,那么你可以编写一个通用的正则表达式。

标签: python regex python-3.x match


【解决方案1】:

$ 是正则表达式中的特殊字符。你应该这样逃避它:

import re
txt='is worth 12$'
pattern=re.compile('12\$')
match=pattern.search(txt)
if match!=None:
    print('ys')
else:
    print('no')

【讨论】:

    【解决方案2】:

    如果您想在正则表达式中使用这些字符中的任何一个作为文字, 你需要用反斜杠转义它们。如果要匹配1+1=2, 正确的正则表达式是 1+1=2。否则,加号有一个特殊的 意思。

    应该是:

    pattern=re.compile('12\$')
    

    【讨论】:

      猜你喜欢
      • 2021-12-30
      • 1970-01-01
      • 2017-07-09
      • 1970-01-01
      • 2019-02-20
      • 2021-12-31
      • 1970-01-01
      • 2020-10-19
      • 2010-10-19
      相关资源
      最近更新 更多