I need to split a string, but ignoring stuff between square brackets. You can imagine this akin to ignoring stuff within quotes.
I came across a solution for quotes;
(\\|)(?=(?:[^"]|"[^"]*")*$)
So;
one|two"ignore|ignore"|three
would be;
one
two"ignore|ignore"
three
However, I am struggling to adapt this to ignore [] instead of ". Partly its down to there being two characters, not one. Partly its down to [] needing to be escaped, and partly its down to me being pretty absolutely awful at regexs.
My goal is to get;
So;
one|two[ignore|ignore]|three
split to;
one
two[ignore|ignore]
three
I tried figuring it out myself but I got into a right mess; (\\|)(?=(?:[^\\[|\\]]|\\|][^\\[|\\]]*\\[|\\])*$)
I am seeing brackets and lines everywhere now.
Help!
This is the adapted version of the ""
regex you posted:
(\|)(?=(?:[^\]]|\[[^\]]*\])*$)
(\|)(?=(?:[^ "]| "[^ "]* ")*$) <- "" version for comparison
You replace the 2nd "
with \\[
and the 1st and 3rd with \\]
使用split方法,您可以使用此模式,因为捕获组显示结果:
\|((?:[^[|]+|\[[^\]]+])*)\|
You should better use String#match
:
s='one|two[ignore|ignore]|three';
m = s.match(/[^|\[]+\[.*?\]|[^|]+/g);
//=> ["one", "two[ignore|ignore]", "three"]
Yet another solution:
"one|two[ignore|ignore]|three".split( /\|(?![^\[]*\])/ )
It uses negative lookahead , unfortunately lookbehind is not supported in JS.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.