0

我需要编写一个正则表达式来用逗号分隔字符串,但不能用空格分隔逗号。我写了一个,但没有成功。

例如:

String testString = "CONGO, THE DEMOCRATIC REPUBLIC OF THE,IRAN, ISLAMIC REPUBLIC OF,KOREA, DEMOCRATIC PEOPLE S REPUBLIC OF,NEPAL,NEW ZEALAND,SRI LANKA";

预期结果:

  1. 刚果民主共和国
  2. 伊朗伊斯兰共和国
  3. 朝鲜民主主义人民共和国
  4. 尼泊尔
  5. 新西兰
  6. 斯里兰卡

我的代码:

public class TestRegEx {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        String testString = "CONGO, THE DEMOCRATIC REPUBLIC OF THE,IRAN, ISLAMIC REPUBLIC OF,KOREA, DEMOCRATIC PEOPLE S REPUBLIC OF,NEPAL,NEW ZEALAND,SRI LANKA";
        String[] output = testString.split("([,][^(,\\s)])+");
        for (String country : output) {
            System.out.println(country);
        }
    }
}

输出:

  1. 刚果民主共和国
  2. 伊朗伊斯兰共和国
  3. 奥里亚,民主人民共和国
  4. EPAL
  5. EW 新西兰
  6. 斯里兰卡
4

2 回答 2

4
,(?!\s)

解释:

匹配任何后面没有空格的逗号。

在此处查看实际操作:http ://regex101.com/r/gW3hJ8

于 2013-10-20T17:02:31.613 回答
2

使用零宽度lookbehind和lookahead

testString.split("(?<! ),(?! )")
于 2013-10-20T16:53:06.843 回答