[英]How to properly exclude group in regex?
我需要在某些文本中匹配某种模式,但是该模式不应具有其他模式。 我在html中使用了某些组,并且html页面未添加新行。 而不是在html中添加新行
所以我在这里遇到麻烦。
我尝试使用此正则表达式:
/\|([^\r\n|]+?(?!<br>))\|/igm
例子是:
test1 | test2 | test3<br>| test4<br>| test5 |<br>test6
应该只匹配| test2 |
| test2 |
和组test2
,但现在也匹配| test4<br>|
| test4<br>|
并且不对| test5 |
| test5 |
。 我需要排除test4匹配,但不知道如何将其与[]
一起使用,因为它忽略了(?!<br>)
。
PS当然| test2 |
| test2 |
也可能是| text1 <span ...>text2</span> text3 |
| text1 <span ...>text2</span> text3 |
,因此将<>
放入[]
不是我需要的解决方案。
您需要的正则表达式应基于经过调适的贪婪令牌 :
/\|((?:(?!<br\s*\/?>)[^\r\n|])*)\|/gi
^^^^^^^^^^^^^^^^^^^^^^^^^^^
令牌是(?:(?!<br\\s*\\/?>)[^\\r\\n|])*
,它与CR / LF / |
以外的任何字符匹配|
( [^\\r\\n|]
否定的字符类解决了这个问题)没有开始<br>
标记序列(或<br >
或<br/>
或<br />
等)。内容与令牌被捕获到#1组中,因为它被捕获括号(...)
包裹了。
JS演示:
var re = /\\|((?:(?!<br\\s*\\/?>)[^\\r\\n|])*)\\|/ig; var str = 'test1 | test2 | test3<br>| test4<br>| test5 |<br>test6|'; var res = []; while ((m = re.exec(str)) !== null) { res.push(m[1]); // Grab Group 1 value only } console.log(res);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.