分裂为“| “不在方括号之间

时间:2022-08-28 21:44:28

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.

然而,我正在努力调整这个以忽略[]而不是“。部分它归结为有两个角色,而不是一个。部分归结为[]需要被转义,部分归结为我非常可怕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!

4 个解决方案

#1


4  

This is the adapted version of the "" regex you posted:

这是您发布的“”正则表达式的改编版本:

(\|)(?=(?:[^\]]|\[[^\]]*\])*$)
(\|)(?=(?:[^ "]| "[^ "]* ")*$) <- "" version for comparison

You replace the 2nd " with \[ and the 1st and 3rd with \]

你用\替换第二个“[和第一个和第三个用\]替换

Working on RegExr

在RegExr上工作

#2


0  

You should better use String#match:

你最好使用String#match:

s='one|two[ignore|ignore]|three';
m = s.match(/[^|\[]+\[.*?\]|[^|]+/g);
//=> ["one", "two[ignore|ignore]", "three"]

#3


0  

Yet another solution:

又一个解决方案:

"one|two[ignore|ignore]|three".split( /\|(?![^\[]*\])/ )

It uses negative lookahead, unfortunately lookbehind is not supported in JS.

它使用负向前瞻,遗憾的是JS不支持lookbehind。

#4


0  

with the split method you can use this pattern since the capturing group is displayed with results:

使用split方法,您可以使用此模式,因为捕获组显示结果:

\|((?:[^[|]+|\[[^\]]+])*)\|

#1


4  

This is the adapted version of the "" regex you posted:

这是您发布的“”正则表达式的改编版本:

(\|)(?=(?:[^\]]|\[[^\]]*\])*$)
(\|)(?=(?:[^ "]| "[^ "]* ")*$) <- "" version for comparison

You replace the 2nd " with \[ and the 1st and 3rd with \]

你用\替换第二个“[和第一个和第三个用\]替换

Working on RegExr

在RegExr上工作

#2


0  

You should better use String#match:

你最好使用String#match:

s='one|two[ignore|ignore]|three';
m = s.match(/[^|\[]+\[.*?\]|[^|]+/g);
//=> ["one", "two[ignore|ignore]", "three"]

#3


0  

Yet another solution:

又一个解决方案:

"one|two[ignore|ignore]|three".split( /\|(?![^\[]*\])/ )

It uses negative lookahead, unfortunately lookbehind is not supported in JS.

它使用负向前瞻,遗憾的是JS不支持lookbehind。

#4


0  

with the split method you can use this pattern since the capturing group is displayed with results:

使用split方法,您可以使用此模式,因为捕获组显示结果:

\|((?:[^[|]+|\[[^\]]+])*)\|