我想通过正则表达式进行java拆分.当我的字符串不在单引号或括号中时,我想在每个逗号上拆分我的字符串.例:
Hello, 'my,',friend,(how ,are, you),(,)
should give:
hello
my,
friend
how, are, you
,
Run Code Online (Sandbox Code Playgroud)
我试过这个:
(?i),(?=([^\'|\(]*\'|\([^\'|\(]*\'|\()*[^\'|\)]*$)
Run Code Online (Sandbox Code Playgroud)
但我不能让它工作(我通过http://java-regex-tester.appspot.com/测试)
有任何想法吗?
嵌套的paranthesises不能被正则表达式分割.它更容易手动拆分.
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;
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.
| 归档时间: |
|
| 查看次数: |
3674 次 |
| 最近记录: |