簡體   English   中英

JS正則表達式,用於捕獲最后一組括號(不包括嵌套)

[英]JS Regex for Capturing Last Set of Parenthesis (Excluding Nested)

因此,我發現了幾篇關於捕獲一組括號內內容的文章,但似乎找不到專門忽略嵌套括號的文章。 另外,我只想捕獲最后一組。

因此,從本質上講,有三個規則:

  1. 捕獲括號內的文本
  2. 僅捕獲LAST括號的內容
  3. 僅在一組括號內捕獲內容(請勿觸摸嵌套)

這是3個示例:

  • Pokemon Blue Version (Gameboy Color)應該返回Gameboy Color
  • Pokemon (International) (Gameboy Color)應該返回Gameboy Color
  • Pokemon Go (iPhone (7))應歸還iPhone (7)

在JS / jQuery( .match() .exec() )中進行編程的正確方法是什么?

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加一個,如果看到( 。則減一。當depth > 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); }); 

這是我在評論中描述的內容,當括號不平衡時(如果需要),可以隨意定義所需的行為:

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) );
} );

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM