首页 > 解决方案 > 反转正则表达式中的捕获组

问题描述

鉴于此(注意捕获组):

/^\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 解决方案。

标签: javascriptarraysregexalgorithmecmascript-6

解决方案


即使我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));


推荐阅读