2012-03-02 35 views
2
html6=""" 
<p<ins style="background:#e6ffe6;">re><code</ins>> 
int aint bint c<ins style="background:#e6ffe6;"></code></ins></p<ins style="background:#e6ffe6;">re</ins>><p>int d</p> 
""" 

HTML6和HTML7是一樣的,只是HTML7有 「\ n」 個Python的重新匹配,空間和新的生產線

html7=""" 
<p<ins style="background:#e6ffe6;">re><code</ins>>int a 
int b 
int c<ins style="background:#e6ffe6;"> 
</code></ins></p<ins style="background:#e6ffe6;">re</ins>> 
<p>int d</p> 
""" 

p_to_pre_code_pattern = re.compile(
"""<p 
<(?P<action_tag>(del|ins)) (?P<action_attr>.*)>re><code</(?P=action_tag)> 
> 
(?P<text>.*?) 
<(?P=action_tag) (?P=action_attr)> 
</code></(?P=action_tag)> 
</p 
<(?P=action_tag) (?P=action_attr)>re</(?P=action_tag)> 
>""",re.VERBOSE) 


print re.match(p_to_pre_code_pattern,html6)  
print re.match(p_to_pre_code_pattern,html7) 

兩個HTML6和HTML7將不匹配? ,但如果我將「\ n」替換爲「」,那麼它們將大大增加。

print re.match(p_to_pre_code_pattern,html6.replace("\n",""))  
print re.match(p_to_pre_code_pattern,html7.replace("\n","")) 

我想知道我應該怎麼改變p_to_pre_code_pattern,我都將HTML6和HTML7無需調用replace("\n",""))匹配嗎?

+0

我不是太上最新與網絡的東西,但將'美麗soup'不這樣做的工具嗎? – Jeff 2012-03-02 16:36:38

+0

你需要添加空格到模式:[這個答案](http://stackoverflow.com/questions/4590298/how-to-ignore-whitespace-in-a-regular-expression-subject-string)似乎相關。 – ChrisP 2012-03-02 16:47:37

回答

1

也許你錯過了re.DOTALL標誌時調用re.compile(..., re.VERBOSE|re.DOTALL)

re.S 
re.DOTALL 

Make the '.' special character match any character at all, including a newline; 
without this flag, '.' will match anything except a newline. 
+0

是的,我發現它,我已經添加到這個'''默認情況下不匹配新行。 – jianjun 2012-03-03 16:05:20