自引用Regex是JavaScript

Cri*_*cia 2 javascript regex context-free-grammar

我想承认

"Str","Int","[Str]","[Int]","[[Str]]",...
Run Code Online (Sandbox Code Playgroud)

我以为我可以做点什么

(Str|Int|\[\1\])
Run Code Online (Sandbox Code Playgroud)

其中\1自引用组.我知道,从形式语言理论,正则表达式不能"指望"因此不可能跟踪的开闭[].

我可能需要一个无上下文语法,我如何在JS中这样做?

Mos*_*sho 5

您可以将匹配组与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');
}
Run Code Online (Sandbox Code Playgroud)

来自MDN:

如果匹配成功,则exec方法返回一个数组并更新正则表达式对象的属性.返回的数组将匹配的文本作为第一个项目,然后为匹配的每个捕获括号中的一个项目包含捕获的文本.

如果匹配失败,则exec方法返回null.

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