gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 05:03:13 26 4
gpt4 key购买 nike

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

我尝试使用 [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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com