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 ?
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With