JS Regex:如果字符串不在引号中,则匹配该字符串,该字符串可能会也可能不会关闭



我正在尝试使用正则表达式来匹配例如"0"字符。但是,我只想匹配不在引号中的 0,这些 0 可能不会关闭。

下面是一个输入字符串的示例,并指示了我想要匹配的 0。

abc"0
"hi 0 bye
"00
0 //match here
If 0 //match here
If (00) //match here, with both zeros being in the same capture group.
hell0 w0rld //match here, each zero being different
"0"
"00"
5*0 // match here
00 //match here, with both zeros being in the same capture group.

我尝试修改其他线程上的片段,但无济于事。首先,我虽然我可以更改(?!B"[^"]*)0(?![^"]*"B)(发布在另一个线程上)以满足我的需求,但我无法。

谢谢。

像这样:

^[^"]*?(0+)[^"]*?$

应该工作。

这基本上匹配包含 0 且不包含引号的行。零在组中捕获。

let str = `abc"0
"hi 0 bye
"00
0 //match here
If 0 //match here
If (00) //match here, with both zeros being in the same capture group.
hell0 w0rld //match here, each zero being different
"0"
"00"
5*0 // match here
00 //match here, with both zeros being in the same capture group.`
str.split("n").forEach(s => console.log((/^[^"]*?(0+)[^"]*?$/g).exec(s)));

最新更新