2010-12-01 36 views
1

我需要匹配以启动任何字符串字符串表达式经常像这样

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' 
+1

我怀疑这是你使用的是什么,因为这正则表达式甚至不进行编译,通过回溯证明。 – 2010-12-01 23:11:20

回答

4

尝试:

/Engine.*?ir_vrn

注意问号。这可以确保在

/引擎&^& ^&^& ir_vrn @ $ @#$ @#ir_vrn!@#!@#

只抓到

/发动&^& ^&^& ir_vrn

而不是

/引擎&^& ^&^& ir_vrn @ $ @#$ @#ir_vrn

2

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

2

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

\'/Engine.+?ir_vrn\' 

此外,您可能要锚定的正则表达式,如果它应该只匹配不仅含有这种模式字符串,但它们是完全一样指定。锚定的正则表达式将是这样的:

^\'/Engine.+ir_vrn\'$ 
2
>>> 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> 
>>> 
0

('\'/Engine[a-zA-Z0-9._+-&/?:=]+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')