如何在没有展望断言的情况下实现此正则表达式?

How can I achieve this regex without a look ahead assertion?

提问人:williamsandonz 提问时间:8/11/2023 最后编辑:Peter Seligerwilliamsandonz 更新时间:8/13/2023 访问量:66

问:

我有正则表达式,它使用展望断言来匹配格式为 {{ x }} 的字符串。正则表达式是/(?<=\{\{\s)[^}\s]+(?=\s*\}\})/gm

如何在不使用“展望”断言的情况下实现此目的?

javascript 匹配 正则表达 式-lookarounds capturing-group

评论

1赞 Luatic 8/11/2023
为什么不简单地使用(捕获您想要的零件,而不是使用环视来排除您不需要的零件)?(我还替换了开头与结尾的一致性)。\{\{\s*([^}\s]+)\s*\}\}\s\s*{{}}

答:

0赞 Alberto Fecchi 8/11/2023 #1

试试这个:

\{\{\s([^}\s]+)\s*\}\}

您的结果将在第一内(其中的规则())

1赞 Heiko Theißen 8/11/2023 #2

除了其他答案之外,如果你想要一个所有“x 值”的列表,你可以通过反复计算来生成一个,这是第一组,其中是匹配项之一。m[1]m

以下带环视和不环视的变体是等效的:

/* With lookaround */
const s = "{{ 1 }}{{ 2 }}";
console.log(s.match(/(?<=\{\{\s*)[^}\s]+(?=\s*\}\})/gm));
/* Without lookaround */
for (var matches = [], m, regex = /\{\{\s*([^}\s]+)\s*\}\}/gm; m = regex.exec(s);)
  matches.push(m[1]);
console.log(matches);

然而,问题仍然存在:你为什么要避免环顾四周?

评论

0赞 williamsandonz 8/11/2023
Safari < 16.4 不支持它
2赞 Peter Seliger 8/11/2023 #3

像 /\{\{\s*([^}]+?) 这样的正则表达式\s*\}\}/g,它确实通过使用 ...{{ x }}

  • 捕获用于定位每个字符的组,这些字符不是右大括号,除了(可选)前导和尾随空格(序列)......和...

  • 懒惰(非贪婪)量词,用于模式终止可选空格(序列)后跟两个右大括号......通过...

  • matchAll 和一个额外的映射ping 任务...

...做到了诀窍。

const sampleDate =
`{{1}} {{}} {{  24 56 48 }}
   {{   245648}}{{ 123  }}`;

console.log(
  // see ... [https://regex101.com/r/uPFdrO/1]

  [...sampleDate.matchAll(/\{\{\s*([^}]+?)\s*\}\}/g)]
    .map(([match, capture]) => capture)
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

将捕获模式从 更改为 to 会强制执行不包含任何空格字符的捕获。懒惰的量词也可以被丢弃......[^}][^}\s]

const sampleDate =
`{{1}} {{}} {{  24 56 48 }}
   {{   245648}}{{ 123  }}`;

console.log(
  // see ... [https://regex101.com/r/uPFdrO/2]

  [...sampleDate.matchAll(/\{\{\s*([^}\s]+)\s*\}\}/g)]
    .map(([match, capture]) => capture)
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

0赞 Ubaid Ali 8/11/2023 #4
const regex = /{{\s([^}\s]+)\s}}/gm;
const input = "text {{ x }} and {{ y }}.";
const matches = input.match(regex);

if (matches) {
    const capturedContent = matches.map(match => match.replace(regex, '$1'));
    console.log(capturedContent);
}