RegEx用逗号分隔一个字符串,用空格忽略逗号 [英] RegEx for split a string with comma ignoring comma with a space
本文介绍了RegEx用逗号分隔一个字符串,用空格忽略逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要编写一个正则表达式来用逗号分隔一个字符串,而不是用空格逗号。我写了一个,但它没有用。
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.
例如:
String testString = "CONGO, THE DEMOCRATIC REPUBLIC OF THE,IRAN, ISLAMIC REPUBLIC OF,KOREA, DEMOCRATIC PEOPLE S REPUBLIC OF,NEPAL,NEW ZEALAND,SRI LANKA";
预期结果:
- CONGO,民主共和国
- 伊朗,伊斯兰共和国
- 朝鲜民主主义人民共和国
- NEPAL
- NEW ZEALAND
- SRI LANKA
- CONGO, THE DEMOCRATIC REPUBLIC OF THE
- IRAN, ISLAMIC REPUBLIC OF
- KOREA, DEMOCRATIC PEOPLE S REPUBLIC OF
- NEPAL
- NEW ZEALAND
- SRI LANKA
我的代码:
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);
}
}
}
输出:
- CONGO,民主共和国
- RAN,ISLAMIC REPUBLIC OF
- OREA,民主人士共和国
- EPAL
- EW ZEALAND
- RI LANKA
- CONGO, THE DEMOCRATIC REPUBLIC OF THE
- RAN, ISLAMIC REPUBLIC OF
- OREA, DEMOCRATIC PEOPLE S REPUBLIC OF
- EPAL
- EW ZEALAND
- RI LANKA
推荐答案
,(?!\s)
说明:
匹配任何未遵循的逗号by whitespace。
Match any comma that is not followed by whitespace.
请点击此处查看: http:/ /regex101.com/r/gW3hJ8
这篇关于RegEx用逗号分隔一个字符串,用空格忽略逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文