2010-12-01 59 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')