简体   繁体   中英

Regex Java String Split by Asterisk

Help is needed.

line.split("*");

I used this line of code to split a string into an asterisk mark. However, I got an error from my compiler. It says, "INVALID REGULAR EXPRESSION: DANGLING META CHARACTER '*'"

How to resolve this problem? Thanks in advance.

* has special meaning in regular expressions. You have to escape it.

line.split("\\*");

试试这个语句:

line.split("\\*");

It is because you used a "*", that is a regular expression. If you want to use this caracter, you need tu put something like that:

line.split("\\*");

* is a meta character in regular expression. It is used for matching 0 or more elements. If you want to use * as a normal character and not as a special character (ie skip its behavior as a meta character) then add escape characters before it.

Eg: String[] split = line.split("\\\\*");

Hope this helps.

As shown in the following table , * has a special meaning, zero or more times .

Greedy Reluctant Possessive Meaning
X? X?? X?+ X, once or not at all
X* X*? X*+ X, zero or more times
X+ X+? X++ X, one or more times
X{n} X{n}? X{n}+ X, exactly n times
X{n,} X{n,}? X{n,}+ X, at least n times
X{n,m} X{n,m}? X{n,m}+ X, at least n but not more than m times

Therefore, you need to escape it with a \ . However, \ too is a special character and therefore you need to put an additional \ to escape \ . Thus, the required pattern becomes \\* .

String[] arr = line.split("\\*");
System.out.println(java.util.Arrays.toString(arr));

Use this

" String data= "Mani*Kum";

String []value= data.split("\\*");

" The output will like this:

value[0]= "Mani";
value[1]= "Kum";

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