鉴于此(注意捕获组):
/^\w+\[\w+\]\[\w+\]\[(\d+)\]\[\w+\]\[(\d+)\]\[\w+\]$/
我想要这个(注意捕获组已经倒置):
/^(\w+\[\w+\]\[\w+\]\[)\d+(\]\[\w+\]\[)\d+(\]\[\w+\])$/
我尝试过的:
str = /^\w+\[\w+\]\[\w+\]\[(\d+)\]\[\w+\]\[(\d+)\]\[\w+\]$/.toString()
noncaptured = [];
captured = [];
insideCapture = false;
for (var i = 0, position = 1; i < str.length; i++) {
if( str.charAt(i) != '(' && insideCapture == false ){
noncaptured.push([position, str.charAt(i) ] );
} else {
if( str.charAt(i) != '(' ){
position += 1;
}
captured.push([position, str.charAt(i) ]);
insideCapture = true;
if( str.charAt(i) == ')' ){
captured.push([position, str.charAt(i)]);
insideCapture = false;
position += 1;
}
}
}
var arr = captured.concat(insideCapture);
arr.sort(function(){
if (a[0] === b[0]) {
return 0;
}
else {
return (a[0] < b[0]) ? -1 : 1;
}
})
我正在寻找一个干净的算法。欢迎使用 ES6 解决方案。
最佳答案
即使我不是100%
确保下一个将适用于您可能需要的所有情况,这可以是一种替代方法:反转所有括号,并在 ^
之后添加括号和之前 $
const str1 = /^\w+\[\w+\]\[\w+\]\[(\d+)\]\[\w+\]\[(\d+)\]\[\w+\]$/.toString();
const str2 = /^\w+(\[\w+\])\[\w+\]\[(\d+)\]\[\w+\]\[(\d+)\]\[\w+\]$/.toString();
const str3 = /^(\w+\[\w+\]\[\w+\]\[\d+\]\[\w+\]\[\d+\]\[\w+\])$/.toString();
const str4 = /^\w+\[\w+\]\[\w+\]\[\d+\]\[\w+\]\[\d+\]\[\w+\]$/.toString();
const replaceMap = {"(": ")", ")": "(", "^": "^(", "$": ")$"};
const reverse = (str) =>
{
return str.replace(/[(,),^, $]/g, function(match)
{
return replaceMap[match];
});
}
console.log(reverse(str1));
console.log(reverse(str2));
console.log(reverse(str3));
console.log(reverse(str4));
关于javascript - 在正则表达式中反转捕获组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54545997/