Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split with character * in string java

Tags:

java

split

I have a string as String placeStr="place1*place2*place3" I want to get array contain place1,place2,place3 as follow:

String[] places=placeStr.split("*");
System.out.println(places[0]);

But it display error E/AndroidRuntime(32118): Caused by: java.util.regex.PatternSyntaxException: Syntax error in regexp pattern near index 1: *

I think cause is character "*". If I change * by -,it display ok. How must I do ?

like image 268
tree hh Avatar asked Mar 29 '26 23:03

tree hh


1 Answers

When you use a Regexp, \* means 0 or more instances of the last defined expression. So for example.

s* means match anything that has 0 or more "s". This will match "ss", "sssss" or "".

When we want to actually search for *, and not use it as an operator, we need to escape it, using the \ character. However, the singular \ is used for special characters (such as \s and \t) so we also need to escape that character, with another \.

This results in:

\ (ignore the next slash)
\ (ignore the star)
* (would be 0 or many, but its been ignored so means the literal.) 

Or in other words

\\*

And in Java, we can use it like this:

String[] places=placeStr.split("\\*");
System.out.println(places[0]);
like image 152
mvieghofer Avatar answered Apr 02 '26 09:04

mvieghofer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!