基于正则表达式拆分字符串时遇到问题。
String str = "1=(1-2,3-4),2=2,3=3,4=4";
Pattern commaPattern = Pattern.compile("\\([0-9-]+,[0-9-]+\\)|(,)") ;
String[] arr = commaPattern.split(str);
for (String s : arr)
{
System.out.println(s);
}预期输出,
1=(1-2,3-4)
2=2
3=3
4=4实际输出,
1=
2=2
3=3
4=4发布于 2013-03-29 16:01:30
此正则表达式将根据需要拆分
,(?![^()]*\\))
------------
|->split with , only if it is not within ()发布于 2013-03-29 16:13:53
这并不是很适合split(...)。请考虑扫描输入并执行match操作:
String str = "1=(1-2,3-4),2=2,3=3,4=4";
Matcher m = Pattern.compile("(\\d+)=(\\d+|\\([^)]*\\))").matcher(str);
while(m.find()) {
String key = m.group(1);
String value = m.group(2);
System.out.printf("key=%s, value=%s\n", key, value);
}它将打印:
key=1, value=(1-2,3-4)
key=2, value=2
key=3, value=3
key=4, value=4发布于 2013-03-29 15:54:19
在这里你必须使用一些前瞻机制。在我看来,你是想用不在括号里的逗号来拆分它。但是你的正则表达式说:
Split on comma OR on comma between numbers in parenthesis 所以你的字符串被分割成4个位置1) (1-2,3-4) 2-4)逗号
https://stackoverflow.com/questions/15699353
复制相似问题