[英]RegEx for capturing values in nested brackets
我试图使用正则表达式来匹配两个字符之间的内部文本,但我得到了错误的文本
我尝试将[Az] *代替。*仅用于匹配内部文本而且它有效。 但我也需要匹配非字母字符。
/\[?(,? ?\[(\[(.+)-(.+)\])\])\]?/g
这是我的正则表达式,我想匹配方括号之间的字符:
[[[ hello-hello]],[[hi -hi]]]
粗体字符是匹配的字符。
我期望匹配匹配1中的[[[ hello-hello ]],[[hi-hi]]]和匹配2中的[[[hello-hello]],[[ hi-hi ]]]匹配。
我会用这样的东西:
\[(?!\[)([^\]]*)\]
这将匹配[
字符,如果没有后跟[
字符。 然后它将匹配在组1中捕获它们的任何数量的非]
字符。然后匹配一个]
字符。
const text = "[[[hello-hello]],[[hi-hi]]]"; const regex = /\\[(?!\\[)([^\\]]*)\\]/g; var match; while (match = regex.exec(text)) { console.log(match); }
或者,您可以省略捕获组并删除每个匹配的第一个和最后一个字符。
const text = "[[[hello-hello]],[[hi-hi]]]"; const regex = /\\[(?!\\[)[^\\]]*\\]/g; console.log( text.match(regex) .map(match => match.slice(1, -1)) );
如果需要[]
之间的所有内容,那么我们可能会将表达式简化为:
(?:\[+)(.+?)(?:\]+)
在这里,我们捕获此捕获组中可能需要的子字符串:
(.+?)
然后,我们使用两个非捕获组在其左侧和右侧添加两个边界:
(?:\[+)
(?:\]+)
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可视化正则表达式:
您可以使用1个捕获组来捕获您的值。
连字符前后的值可以是使用否定字符类匹配的匹配\\[([^][\\n-]+
匹配不是开括号或右括号,连字符或换行符。
在你的模式中,你使用一个点,它将匹配除换行符之外的任何字符,因此否定的字符类包含一个换行符以防止交叉行。
\[([^\][\n-]+-[^\][\n-]+)]
说明
\\[
匹配[
(
开始捕获组
[^\\][\\n-]+
不否定的字符类,匹配1+倍]
, [
, -
或换行符 -
比赛-
[^\\][\\n-]+
匹配1+倍不]
, [
, -
或换行符 )
关闭捕获组 ]
匹配]
char const regex = /\\[([^\\][\\n-]+-[^\\][\\n-]+)]/g; const str = `[[[hello-hello]],[[hi-hi]]]`; let m; while ((m = regex.exec(str)) !== null) { if (m.index === regex.lastIndex) { regex.lastIndex++; } console.log(m[1]); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.