简体   繁体   中英

How to group two characters in java regular expression?

I have to split a string using 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.

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?

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: | )

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. It takes a regular expression as parameter. In your case, you want to match a comma and one space, therefore your regex is ",\\\\s" .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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