Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

java - RegEx for split a string with comma ignoring comma with a space

I need to write a regular expression to split a string with comma but not comma with space.I wrote one , but it did not work out.

E.g:

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

Expected Result:

  1. CONGO, THE DEMOCRATIC REPUBLIC OF THE
  2. IRAN, ISLAMIC REPUBLIC OF
  3. KOREA, DEMOCRATIC PEOPLE S REPUBLIC OF
  4. NEPAL
  5. NEW ZEALAND
  6. SRI LANKA

My code:

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);
        }
    }
}

OUTPUT:

  1. CONGO, THE DEMOCRATIC REPUBLIC OF THE
  2. RAN, ISLAMIC REPUBLIC OF
  3. OREA, DEMOCRATIC PEOPLE S REPUBLIC OF
  4. EPAL
  5. EW ZEALAND
  6. RI LANKA
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
,(?!s)

Explanation:

Match any comma that is not followed by whitespace.

See it in action here: http://regex101.com/r/gW3hJ8


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...