2015-04-15 47 views
0

我想从html中取段落或div,但是如果它不包含表单。 例如:正则表达式匹配没有子字符串的字符串

<p><form>I don't want this text</form>and not this text</p> 
<p>I want to take this text</p> 

我有工作变体,没有窗体过滤器。

/(?:<(?:p|div)[^>]*>)(.*)(?:<\/(?:p|div)>)/iu 

以及不变形与过滤

/(?:<(?:p|div)[^>]*>)((?:.(?!<form))*)(?:<\/(?:p|div)>)/iu 

你能帮助我吗?

+0

究竟是不是工作在哪些情况下没有给出错误的结果(什么是在这些情况下,预期的结果) – Keelan

+1

http://stackoverflow.com/questions/1732 348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 –

回答

1

警告:用Regexp解析HTML一直是,而且永远是一个坏主意。

这是你的正则表达式略加修改的版本:

/(?:<(?:p|div)[^>]*>)(?!.*\<form\>)(.*)(?:<\/(?:p|div)>)/iu 

我改进它,让你赶上包含文字“形式的任何段落(而不是标签)与尝试。这个测试:??

<p><form>I don't want this text</form>and not this text</p> 
<p>I want to take this text even if it contains the "form" word!</p> 
<p>I want to take this text</p> 
+0

谢谢,我突然明白我在看html,但正则表达式使用shortcodes :)对不起,我的注意力不集中。 –

+1

@StetsenkoStas如果这解决了您的问题,请通过单击答案左侧的复选标记来接受它。 –

相关问题