【问题标题】:Regular expression for a string like this像这样的字符串的正则表达式
【发布时间】:2010-12-01 23:00:13
【问题描述】:

我需要匹配以下开头的任何字符串:

'/Engine

并以:

结尾
ir_vrn'

我用过这个:

 vrn_page = re.compile('\'/Engine[a-zA-Z0-9._+-&/?:=]+ir_vrn\'')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.6/re.py", line 190, in compile
    return _compile(pattern, flags)
  File "/usr/lib/python2.6/re.py", line 245, in _compile
    raise error, v # invalid expression
sre_constants.error: bad character range

但不适用于此字符串:

'/Engine/page/im/pop_mostra.php?P_=9078&P_Utentevisitatore=1702795&loto=http://s1.example.com/utloto/9/9078/Media/7df4164ecb81a5992280a1ce81120d05-3a5fa4377a23242690a273a82ea5d607&type=ir_vrn'

【问题讨论】:

  • 我怀疑那是您使用的,因为该正则表达式甚至无法编译,正如回溯所证明的那样。

标签: python regex python-3.x


【解决方案1】:

试试:

/Engine.*?ir_vrn

注意问号。这确保在

/Engined&^&^&^&ir_vrn@$@#$@#ir_vrn!@#!@#

它只捕获

/Engined&^&^&^&ir_vrn

而不是

/Engined&^&^&^&ir_vrn@$@#$@#ir_vrn

【讨论】:

    【解决方案2】:

    它不起作用,因为你对中间部分的限制太高了。试试这个(. 代表正则表达式中的“任何字符”):

    \'/Engine.+?ir_vrn\'
    

    此外,如果正则表达式只匹配不仅包含此模式,而且完全符合指定的字符串,您可能希望锚定它。锚定的正则表达式是这样的:

    ^\'/Engine.+ir_vrn\'$
    

    【讨论】:

      【解决方案3】:
      >>> import re
      >>> regexp = "'/Engine.*ir_vrn'"
      >>> re.match(regexp, "'/Engineir_vrn'")
      <_sre.SRE_Match object at 0x101e2f9f0>
      >>> re.match(regexp, "'/Engine/page/im/pop_mostra.php?P_=9078&P_Utentevisitatore=1702795&loto=http://s1.example.com/utloto/9/9078/Media/7df4164ecb81a5992280a1ce81120d05-3a5fa4377a23242690a273a82ea5d607&type=ir_vrn'")
      <_sre.SRE_Match object at 0x101e2f988>
      >>> 
      

      【讨论】:

        【解决方案4】:

        为什么不^\'/Engine.*ir_vrn\'$

        【讨论】:

          【解决方案5】:

          ('\'/Engine[a-zA-Z0-9._+-&amp;/?:=]+ir_vrn\'')有问题是因为?:+-.在python正则表达式中有特定的含义。您逃脱了/,但没有逃脱这些失败的其他字符。

          另外,你在滥用字符范围:

          [A-Za-z0-9]+ 将匹配一个或多个字母数字字符。 [a-zA-Z0-9.] 在语法上不正确。 [a-zA-Z0-9\.] 有效。既然你想要可打印的字符,\S 会很好用。

          vrn_page = re.compile(r'\/Engine\S+ir_vrn')

          【讨论】:

            猜你喜欢
            • 2021-02-21
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-02-09
            相关资源
            最近更新 更多