简体   繁体   English

如何正确排除正则表达式中的组?

[英]How to properly exclude group in regex?

I need to match in some text some pattern, but this pattern should not have another pattern. 我需要在某些文本中匹配某种模式,但是该模式不应具有其他模式。 I use in html some groups and html page does not add new line. 我在html中使用了某些组,并且html页面未添加新行。 Rather than new line in html added 而不是在html中添加新行
so I get trouble here. 所以我在这里遇到麻烦。

I try to use this regex: 我尝试使用此正则表达式:

/\|([^\r\n|]+?(?!<br>))\|/igm

and example is: 例子是:

test1 | test2 | test3<br>| test4<br>| test5 |<br>test6

Should be matching only | test2 | 应该只匹配| test2 | | test2 | and group test2 , but right now also matching | test4<br>| 和组test2 ,但现在也匹配| test4<br>| | test4<br>| and not right | test5 | 并且不对| test5 | | test5 | . I need to exclude test4 match, but don't know how to use it with [] because it ignored (?!<br>) . 我需要排除test4匹配,但不知道如何将其与[]一起使用,因为它忽略了(?!<br>)

PS of course | test2 | PS当然| test2 | | test2 | also may be | text1 <span ...>text2</span> text3 | 也可能是| text1 <span ...>text2</span> text3 | | text1 <span ...>text2</span> text3 | , so placing <> into [] is not a solution I need. ,因此将<>放入[]不是我需要的解决方案。

The regex you need should be based on a tempered greedy token : 您需要的正则表达式应基于经过调适的贪婪令牌

/\|((?:(?!<br\s*\/?>)[^\r\n|])*)\|/gi
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^

See the regex demo 正则表达式演示

The token is (?:(?!<br\\s*\\/?>)[^\\r\\n|])* and it matches any character other than a CR/LF/ | 令牌是(?:(?!<br\\s*\\/?>)[^\\r\\n|])* ,它与CR / LF / |以外的任何字符匹配| (the [^\\r\\n|] negated character class accounts for that) that is not starting a <br> tag sequence (or <br > or <br/> or <br /> , etc.) The contents matched with the token are captured into group #1 since it is wrapped with a capturing parentheses (...) . [^\\r\\n|]否定的字符类解决了这个问题)没有开始<br>标记序列(或<br ><br/><br />等)。内容与令牌被捕获到#1组中,因为它被捕获括号(...)包裹了。

JS demo: 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM