我想通过正则表达式进行 java 拆分。 当它不在单引号或方括号中时,我想在每个逗号上拆分我的字符串。 示例:
Hello, 'my,',friend,(how ,are, you),(,)
should give:
hello
my,
friend
how, are, you
,
我试过这个:
(?i),(?=([^\'|\(]*\'|\([^\'|\(]*\'|\()*[^\'|\)]*$)
但我无法让它工作(我通过 http://java-regex-tester.appspot.com/ 测试)
有什么想法吗?
最佳答案
嵌套的括号不能被正则表达式分割。手动拆分它们更容易。
public static List<String> split(String orig) {
List<String> splitted = new ArrayList<String>();
int nextingLevel = 0;
StringBuilder result = new StringBuilder();
for (char c : orig.toCharArray()) {
if (c == ',' && nextingLevel == 0) {
splitted.add(result.toString());
result.setLength(0);// clean buffer
} else {
if (c == '(')
nextingLevel++;
if (c == ')')
nextingLevel--;
result.append(c);
}
}
// Thanks PoeHah for pointing it out. This adds the last element to it.
splitted.add(result.toString());
return splitted;
}
希望这对您有所帮助。
关于java正则表达式,仅当不在引号或括号中时才以逗号分隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16107771/