javascript 如何分割字符串而忽略括号中的部分?

f2uvfpb9  于 2023-05-12  发布在  Java
关注(0)|答案(5)|浏览(156)

我有一个字符串,我想分割成一个数组使用逗号作为分隔符。我不希望括号之间的字符串部分被拆分,即使它们包含逗号。
例如:

"bibendum, morbi, non, quam (nec, dui, luctus), rutrum, nulla"

应变为:

["bibendum", "morbi", "non", "quam (nec, dui, luctus)", "rutrum", "nulla"]

但是当我使用基本的.split(",")时,它返回:

["bibendum", " morbi", " non", " quam (nec", " dui", " luctus)", " rutrum", " nulla"]

我需要它返回:

["bibendum", " morbi", " non", " quam (nec, dui, luctus)", " rutrum", " nulla"]

感谢你的帮助。

r1wp621o

r1wp621o1#

var regex = /,(?![^(]*\)) /;
var str = "bibendum, morbi, non, quam (nec, dui, luctus), rutrum, nulla"; 

var splitString = str.split(regex);

给你正则表达式的解释:

,     //Match a comma
(?!   //Negative look-ahead. We want to match a comma NOT followed by...
[^(]* //Any number of characters NOT '(', zero or more times
\)    //Followed by the ')' character
)     //Close the lookahead.
dsf9zpds

dsf9zpds2#

您不需要为此使用花哨的正则表达式。

s="bibendum, morbi, non, quam (nec, dui, luctus), rutrum, nulla" 
var current='';
var parenthesis=0;
for(var i=0, l=s.length; i<l; i++){ 
  if(s[i] == '('){ 
    parenthesis++; 
    current=current+'(';
  }else if(s[i]==')' && parenthesis > 0){ 
    parenthesis--;
    current=current+')';
  }else if(s[i] ===',' && parenthesis == 0){
    console.log(current);current=''
  }else{
    current=current+s[i];
  }   
}
if(current !== ''){
  console.log(current);
}

将console.log更改为数组串联或任何您想要的内容。

hivapdat

hivapdat3#

而不是专注于你不想要的东西,通常更容易表达为正则表达式你想要的东西,并使用全局正则表达式match

var str = "bibendum, morbi, non, quam (nec, dui, luctus), rutrum, nulla";
str.match(/[^,(]+(?:\(.*?\))?/g) // the simple one
str.match(/[^,\s]+(?:\s+\([^)]*\))?/g) // not matching whitespaces
9njqaruj

9njqaruj4#

var start = "bibendum, morbi, non, quam (nec, dui, luctus), rutrum, nulla";
start = start.replace(/ /g,'');
console.log(start);

var front = start.substring(0,start.lastIndexOf('(')).split(',');
var middle = '('+start.substring(start.lastIndexOf('(')+1,start.lastIndexOf(')'))+')';
var end = start.substring(start.lastIndexOf(')')+2,start.length).split(',');
console.log(front)
console.log(middle)
console.log(end)
return front.concat(middle,end);
zaqlnxep

zaqlnxep5#

我不喜欢在我的代码中有大的不透明的正则表达式,所以我使用了不同的解决方案。它仍然使用正则表达式,但我认为它更加透明。
我使用了一个更简单的正则表达式,用一个特殊的字符串替换括号内的逗号。然后我用逗号分割字符串,然后在每个结果标记中用逗号替换特殊字符串。

splitIgnoreParens(str: string): string[]{
    const SPECIAL_STRING = '$REPLACE_ME';

    // Replaces a comma with the special string
    const replaceComma = s => s.replace(',',SPECIAL_STRING);
    // Vice versa
    const replaceSpecialString = s => s.replace(SPECIAL_STRING,',');

    // Selects any text within parenthesis
    const parenthesisRegex = /\(.*\)/gi;

    // Withing all parenthesis, replace comma with special string.
    const cleanStr = str.replace(parenthesisRegex, replaceComma);
    const tokens = cleanStr.split(',');
    const cleanTokens = tokens.map(replaceSpecialString);

    return cleanTokens;
}

相关问题