javascript - 反转正则表达式中的捕获组
问题描述
鉴于此(注意捕获组):
/^\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));
推荐阅读
- c# - ASP.Net Core 从构造函数返回结果
- ember.js - 是否可以在 Ember 中将 Torii 与 FastBoot 一起使用?
- python - “a and a or b”的目的是什么?
- html - 如何使中间TD高于侧面TD?
- rabbitmq - 关于 RabbitMQ 通道的最佳实践
- c# - 附加没有硬编码值的字符串
- performance - 在python中超过时间限制
- android - 如何使 react-router 的 NavLink 在 Android 移动浏览器中打开应用意图?
- git - 如何将代码从本地 git 推送到 github,不包括媒体文件夹?
- php - Laravel,如何从另一个控制器调用函数