【发布时间】:2020-09-24 09:17:14
【问题描述】:
我有这个正则表达式:/{(?:{(?:.*?)?)?$/g。
请注意,我正在尝试延迟匹配最内层组中的 .*?。
但它的行为不像我期望的那样:
const regex = /{(?:{(?:.*?)?)?$/g;
let match = "{{abc{".match(regex)
// expected: [ "{" ]
// actual: [ "{{abc{" ]
match = "{{abc{{".match(regex)
// expected: [ "{{" ]
// actual: [ "{{abc{{" ]
match = "{{abc{{def".match(regex)
// expected: [ "{{def" ]
// actual: [ "{{abc{{def" ]
我正在使用这个正则表达式来匹配{、{{ 或{{something(如果它位于字符串的末尾(不考虑多行字符串))
这可能是因为字符串是从左到右匹配的,但是有没有一种优雅的方式来获得预期的行为?
编辑:
在所选解决方案中使用正则表达式可以解决上述问题,但如果最后一个 {{ 之后的字符串包含一个或多个 { 而不是彼此跟随,则会失败。
示例:
const regex = /{(?:{(?:[^{]*?)?)?$/g;
let match = "{{abc{{de{f".match(regex)
// expected: [ "{{de{f" ]
// actual: null
match = "{{abc{{de{f{g".match(regex)
// expected: [ "{{de{f{g" ]
// actual: null
【问题讨论】:
-
$使其匹配到最后。正则表达式引擎从左到右解析字符串,因此它从匹配的最左边的字符开始匹配。使用{(?:{(?:[^{}]*)?)?$。或{{?[^{}]*$。见demo。
标签: javascript node.js regex string regex-group