【问题标题】:Regular expression to match the string [closed]匹配字符串的正则表达式[关闭]
【发布时间】:2012-01-21 21:19:04
【问题描述】:

请提供正则表达式以匹配以下字符串。

"self.unsupported_cmds = [r'\s*clns\s+routing',"

提前致谢。

我尝试了以下,

re.match("^self\.unsupported\_cmds| ?=\ ?\[r\'.*\,", line)

其中 line 是上面提到的字符串。它没有用。

我没有收到任何错误或异常,只是与上面给出的字符串不匹配。

【问题讨论】:

  • 您自己尝试过什么吗?请参阅常见问题解答:stackoverflow.com/faq
  • 我试过了,re.match("^self\.unsupported_cmds\ ?=\ ?[r\'.*\,", line)
  • 您应该在问题中记录这一点,并描述您的代码遇到的特定问题(错误消息、异常等)。
  • 匹配条件是什么?因为您没有说明 wim 的答案是有效的。

标签: python regex


【解决方案1】:

我不确定你的问题是什么,我认为不是正则表达式。

你真的只调用这段代码吗?

re.match("^self\.unsupported\_cmds| ?=\ ?\[r\'.*\,", line)

如果是,试试这个:

if(re.match("^self\.unsupported\_cmds| ?=\ ?\[r\'.*\,", line)):
    print "Match"

对我来说这是返回匹配,这意味着你的正则表达式正在工作(但它是一个奇怪的正则表达式!)

也许你应该看看docs.python.org/library/re.html

【讨论】:

    【解决方案2】:

    这是获得它的多种方法之一:

    >>> x = r'''"self.unsupported_cmds = [r'\s*clns\s+routing',"'''
    >>> print x
    "self.unsupported_cmds = [r'\s*clns\s+routing',"
    >>> import re
    >>> pattern = re.escape(x)
    >>> re.match(pattern, x)
    <_sre.SRE_Match object at 0x7ffca3f66098>
    >>> print pattern
    \"self\.unsupported\_cmds\ \=\ \[r\'\\s\*clns\\s\+routing\'\,\"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-10
      • 1970-01-01
      • 2023-04-02
      • 2012-06-05
      • 2013-12-25
      • 1970-01-01
      相关资源
      最近更新 更多