0

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

2 Answers 2

4
,(?!\s)

Explanation:

Match any comma that is not followed by whitespace.

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

Sign up to request clarification or add additional context in comments.

3 Comments

Testing multiple whitespaces is useless since one is enough. You don't need capturing parenthesis too.
You're right on both accounts. Edited my answer. Thanks for pointing it out.
It is not even compiling... Can you update the answer @gry?
2

Use zero width lookbehind and lookahead

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

1 Comment

sam_mit - please accept the answer if it was the correct one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.