2012-03-02 55 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