无法使我的正则表达式正常工作

时间:2016-10-19 18:52:32

标签: java regex

我得到了一些用逗号分隔的数据,但是我需要在“不要分割数据”之间的逗号。

所以:“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));
    }
}

第一组可以工作,但我不能让第二组工作,因为我需要:([^,] +)(除了,一次或多次) 也没有任何东西作为空字符串。这甚至可能吗?

2 个答案:

答案 0 :(得分: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); 

请参阅online Java demo

答案 1 :(得分:0)

您似乎只需将html()替换为+,并将双引号&#34; 添加到您的第二个捕获组:

*

检查其工作原理here

相关问题