[英]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.