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:
- CONGO, THE DEMOCRATIC REPUBLIC OF THE
- IRAN, ISLAMIC REPUBLIC OF
- KOREA, DEMOCRATIC PEOPLE S REPUBLIC OF
- NEPAL
- NEW ZEALAND
- 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:
- CONGO, THE DEMOCRATIC REPUBLIC OF THE
- RAN, ISLAMIC REPUBLIC OF
- OREA, DEMOCRATIC PEOPLE S REPUBLIC OF
- EPAL
- EW ZEALAND
- RI LANKA
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…