Reputation: 338
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:
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:
Upvotes: 0
Views: 2275
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
Reputation: 32787
Use zero width lookbehind and lookahead
testString.split("(?<! ),(?! )")
Upvotes: 2