【问题标题】:Python re-match with space and new linePython重新匹配空格和换行
【发布时间】:2012-03-21 03:13:24
【问题描述】:
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"

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,以便在不调用replace("\n","")) 的情况下同时匹配html6 和html7?

【问题讨论】:

  • 我对网络东西不太了解,但beautiful soup 不是这个工具吗?
  • 您需要在模式中添加空格:This answer 似乎相关。

标签: python regex


【解决方案1】:

也许你在调用 re.compile(..., re.VERBOSE|re.DOTALL)

时错过了 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.

【讨论】:

  • 是的,我找到了,我已经添加了,. 默认不会匹配新行。
猜你喜欢
  • 2019-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-21
  • 1970-01-01
  • 2012-10-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多