所以我找到了一些文章,谈论捕获一组括号内的内容,但似乎找不到一个特别忽略嵌套括号的内容。另外,我想只拍摄最后一组。
所以实质上有三条规则:
以下是3个例子:
Pokemon Blue Version (Gameboy Color)
应该返回Gameboy Color
Pokemon (International) (Gameboy Color)
应该返回Gameboy Color
Pokemon Go (iPhone (7))
应该返回iPhone (7)
在JS / jQuery(.match()
,.exec()
)中编程的正确方法是什么?
答案 0 :(得分:3)
https://regex101.com/r/UOFxWC/2
var strings = [
'Pokemon Blue Version (Gameboy Color)',
'Pokemon (International) (Gameboy Color)',
'Pokemon Go (iPhone (7))'
];
strings.forEach(function(string) {
var re = /\(([^)]+\)?)\)(?!.*\([^)]+\))/ig;
var results = re.exec(string);
console.log(results.pop());
});
或者,您可以自己解析字符串。我们的想法是从后面开始,每当您看到)
向depth
添加一个时,如果看到(
,则减1。当深度为> 0
时,将当前字符添加到临时字符串中。因为你只想要最后一组,所以我们可以在完全匹配时拯救(break
),即子字符串存在,深度回零。请注意,这不适用于损坏的数据:当组不平衡时,您将获得奇怪的结果。所以你必须确保你的数据是正确的。
var strings = [
'Pokemon Blue Version (Gameboy Color)',
'Pokemon (International) (Gameboy Color)',
'Pokemon Go (iPhone (7))',
'Pokemon Go (iPhon(e) (7))',
'Pokemon Go ( iPhone ((7)) )'
];
strings.forEach(function(string) {
var chars = string.split('');
var tempString = '';
var depth = 0;
var char;
while (char = chars.pop()) {
if (char == '\(') {
depth--;
}
if (depth > 0) {
tempString = char + tempString;
}
if (char == '\)') {
depth++;
}
if (tempString != '' && depth === 0) break;
}
console.log(tempString);
});
答案 1 :(得分:1)
这是我在评论中描述的内容,随意定义括号不平衡时所需的行为(如果需要):
function lastparens(str) {
var count = 0;
var start_index = false;
var candidate = '';
for (var i = 0, l = str.length; i < l; i++) {
var char = str.charAt(i);
if (char == "(") {
if (count == 0) start_index = i;
count++;
} else if (char == ")") {
count--;
if (count == 0 && start_index !== false)
candidate = str.substr (start_index, i+1);
if (count < 0 || start_index === false) {
count = 0;
start_index = false;
}
}
}
return candidate;
}
测试用例:
var arr = [ 'Pokemon Blue Version (Gameboy Color)',
'Pokemon (International) (Gameboy Color)',
'Pokemon Go (iPhone (7))',
'Pokemon Go ( iPhon(e) (7) )',
'Pokemon Go ( iPhone ((7)) )',
'Pokemon Go (iPhone (7)' ];
arr.forEach(function (elt, ind) {
console.log( elt + ' => ' + lastparens(elt) );
} );