简体   繁体   English

如何在Java正则表达式中将两个字符分组?

[英]How to group two characters in java regular expression?

I have to split a string using Java. 我必须使用Java拆分字符串。

Suppose I have 假设我有

"India, Russia, US,UK, Asia"

and i want output like 我想要输出像

India 
Russia
US,Uk 
Asia

I mean i have to split it for the combination of "comma" and "space" only. 我的意思是我只能将其拆分为“逗号”和“空格”的组合。

The string. 字符串。 split(String regex) method should do what you need. split(String regex)方法应该可以满足您的需求。

So, doing something like so, should work: 因此,执行类似的操作应该可以:

String str = "India, Russia, US,UK , Asia"
String[] countries = str.split(",\\s+");

This will split a string upon finding a comma followed by one or more spaces. 找到一个逗号后跟一个或多个空格时,这将拆分字符串。

How to group two characters in java regular expression? 如何在Java正则表达式中将两个字符分组?

You just put them after each other. 您只是将它们互相紧贴。

(This will not cause the split to split on either one of the characters. For that you need to put it in a character class [...] , or combine them with the or operator: | ) (这不会导致拆分拆分到任一字符上。为此,您需要将其放入字符类[...] ,或将其与or运算符结合使用: |

I have to split it for the combination of "comma" and "space" only. 我只能将其拆分为“逗号”和“空格”的组合。

Then put a comma, and then a space after each other: 然后加一个逗号,然后一个空格:

str.split(", ");

Just use the String split method. 只需使用String split方法。 It takes a regular expression as parameter. 它以正则表达式为参数。 In your case, you want to match a comma and one space, therefore your regex is ",\\\\s" . 在您的情况下,您要匹配一个逗号和一个空格,因此您的正则表达式为",\\\\s"

String countries = "India, Russia, US,UK , Asia"
String[] countryArray = countries.split(",\\s");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM