我得到了一些用逗号分隔的数据,但我需要“”之间的逗号才能不拆分数据。
因此:“A,B”应该是“A,B”,而 A,B 应该拆分为“A”、“B”。
我遇到的麻烦是,如果一行中有多个逗号,那么空位将被忽略:A,,B 分成“A”、“B” 但我需要它是:“A”、“”、“B”
这是我的代码:
ArrayList<String> tokens = new ArrayList<String>();
String regex = "\"([^\"]*)\"|([^,]+)";
Matcher m = Pattern.compile(regex).matcher(line);
while (m.find()) {
if (m.group(1) != null) {
tokens.add(m.group(1));
}
else {
tokens.add(m.group(2));
}
}
第一组工作,但我无法让第二组工作,因为我需要:([^,]+)(除了 ,一次或几次) 也没有包含任何内容作为空字符串。这可能吗?
最佳答案
你只需要在你的选择中添加另一个分支:(?<=,)(?=,)
匹配两个逗号之间的空格。
String line = "A,,B";
ArrayList<String> tokens = new ArrayList<String>();
String regex = "\"([^\"]*)\"|[^,]+|(?<=,)(?=,)"; // <= No need for Group 2
Matcher m = Pattern.compile(regex).matcher(line);
while (m.find()) {
if (m.group(1) != null) {
tokens.add(m.group(1));
}
else {
tokens.add(m.group(0)); // <= Note that we can grab the whole match here
}
}
System.out.println(tokens);
关于java - 无法让我的正则表达式正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40139377/