简体   繁体   中英

Split with character * in string java

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]);

Try this using the backslashes \\\\ :

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

use backslashes which changes the meaning of a particular character in java

ie String[] places=placeStr.split("\\\\*"); It will change the meaning of *

you will need to escape the asterisk with a back slash (and then escape that with another backslash)

String[] places=placeStr.split("\\*");

This should allow you to get the results you need

PS this will only print the first element

System.out.println(places[0]);

putting it into a for loop will allow you to print them all

int count 0;
for(string place : places) {
    System.out.println(places[count]);
    count++
}

I think the print code will work although I haven't tested it

I see at least to correct answers to this problem, good for them however the concepts of why their answers are correct.

As pointed out, the * has special meaning, that is it matches all characters. So in your case, you need to escape it in order for the reg ex engine to match exactly it, so you need * in the regular expression.

However, if you attempt to do:

String[] places=placeStr.split("\*");

you will get a compile error. This is because the \\ character has special meanings in strings. So you need to escape it.

This is how you arrive at:

String[] places=placeStr.split("\\*");

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