我试图使用正则表达式来匹配两个字符之间的内部文本,但我得到了错误的文本
我尝试使用 [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);
正则表达式
如果不需要此表达式,可以在 regex101.com 中对其进行修改/更改.
正则表达式电路
jex.im可视化正则表达式:
关于javascript - 用于捕获嵌套括号中的值的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56306653/