javascript - 用于捕获嵌套括号中的值的正则表达式

标签 javascript regex regex-lookarounds regex-group regex-greedy

我试图使用正则表达式来匹配两个字符之间的内部文本,但我得到了错误的文本

我尝试使用 [A-z]* 而不是 .* 来仅匹配内部文本并且它起作用了。但我也需要匹配非字母字符。

/\[?(,? ?\[(\[(.+)-(.+)\])\])\]?/g

这是我的正则表达式,我想匹配方括号之间的字符:

[[[hello-hello]],[[hi-hi]]]

加粗的字符是匹配的。

I'd expect to match [[[hello-hello]],[[hi-hi]]] in match 1 and [[[hello-hello]],[[hi-hi]]] in match two.

最佳答案

如果需要 [] 之间的所有内容,那么我们可以将表达式简化为 maybe:

(?:\[+)(.+?)(?:\]+)

在这里,我们在此捕获组中捕获可能需要的子字符串:

(.+?)

然后,我们使用两个非捕获组在其左右两侧添加两条边界:

(?:\[+)
(?:\]+)

演示

const regex = /(?:\[+)(.+?)(?:\]+)/g;
const str = `[[[hello-hello]]
[[hi-hi]]]
[[hi hi]]]`;
const subst = `$1`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);

enter image description here

正则表达式

如果不需要此表达式,可以在 regex101.com 中对其进行修改/更改.

正则表达式电路

jex.im可视化正则表达式:

enter image description here

关于javascript - 用于捕获嵌套括号中的值的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56306653/

相关文章:

javascript - console.log 返回一个额外的未定义

R - 在矩阵中的特定列上使用 APPLY

regex - 如何使用 Neovim 正则表达式进行单独选择(两个字符不连续)?

javascript - 视障人士无法访问 Asp 验证摘要

JavaScript 日期 + 7 天

javascript - 与 JavaScript 相比,正则表达式在 Ruby 中表现不佳

regex - 使用正则表达式 bash 将字符串提取到变量

正则表达式替换匹配项,但也会忽略引号内的匹配项

正则表达式查找匹配文件扩展名的文件,除非文件名包含字符串

javascript - Revolution Slider JS 冲突