sampathlk
sampathlk

Reputation: 338

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

Upvotes: 0

Views: 2275

Answers (2)

Kai Sassnowski
Kai Sassnowski

Reputation: 280

,(?!\s)

Explanation:

Match any comma that is not followed by whitespace.

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

Upvotes: 4

Anirudha
Anirudha

Reputation: 32787

Use zero width lookbehind and lookahead

testString.split("(?<! ),(?! )")

Upvotes: 2

Related Questions