gpt4 book ai didi

javascript - JavaScript 中的自引用正则表达式

转载 作者:行者123 更新时间:2023-11-29 17:06:41 27 4
gpt4 key购买 nike

我要认识

"Str","Int","[Str]","[Int]","[[Str]]",...

我以为我可以做类似的事情

(Str|Int|\[\1\])

其中 \1 self 引用组。我从形式语言理论知道正则表达式不能“计数”,因此不可能跟踪开始和结束 []

我可能需要上下文无关语法,我该如何在 JS 中实现?

最佳答案

您可以将匹配组与 RegExp.prototype.exec() 结合使用.

var myString = "[[Str]]";
var myRegexp = /(\[*)Str(\]*)/g;
var match = myRegexp.exec(myString);
if (match[1] !== undefined && match[2] !== undefined &&
match[1].length === match[2].length) {
console.log('valid string');
}

来自 MDN:

If the match succeeds, the exec method returns an array and updates properties of the regular expression object. The returned array has the matched text as the first item, and then one item for each capturing parenthesis that matched containing the text that was captured.

If the match fails, the exec method returns null.

String.prototype.replace()可以类似地使用。

关于javascript - JavaScript 中的自引用正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24222917/

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