我有一个字符串,我想使用逗号作为分隔符将其拆分为一个数组。 我不希望括号之间的字符串部分被分割,即使它们包含逗号。
例如:
"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"]
感谢您的帮助。
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.
为此,您不需要花哨的正则表达式。
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 更改为数组串联或您想要的任何内容。
与其专注于你做的不想要的,通常更容易用正则表达式表达你想要的,并使用全局正则表达式
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
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);
我不喜欢在代码中使用大量不透明的正则表达式,因此我使用了不同的解决方案。它仍然使用正则表达式,但我认为更透明。
我使用更简单的正则表达式将括号内的任何逗号替换为特殊字符串。然后我用逗号分割字符串,然后在每个生成的标记中用逗号替换特殊字符串。
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;
}
我有一个类似的问题,我用这个模块解决了它
@jondotsoy/splitg
,如果它用块(括号,正方形或方括号)括起来,可以防止分裂
import { splitg } from "@jondotsoy/splitg";
const parts = splitg("This is split (but this not)")
// => [
// "This",
// "is",
// "split",
// "(but this not)"
// ]
在这里尝试更多https://jondotsoy.github.io/splitg/?q=This+is+split+(but+this+not)