Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 868
princepiero Avatar asked Mar 19 '13 05:03

princepiero


People also ask

How split a string in regex?

To split a string by a regular expression, pass a regex as a parameter to the split() method, e.g. str. split(/[,. \s]/) . The split method takes a string or regular expression and splits the string based on the provided separator, into an array of substrings.

What does \\ mean in Java regex?

Backslashes in Java. The backslash \ is an escape character in Java Strings. That means backslash has a predefined meaning in Java. You have to use double backslash \\ to define a single backslash. If you want to define \w , then you must be using \\w in your regex.

Can you use regex in Split Java?

split(String regex) method splits this string around matches of the given regular expression. This method works in the same way as invoking the method i.e split(String regex, int limit) with the given expression and a limit argument of zero. Therefore, trailing empty strings are not included in the resulting array.


3 Answers

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

line.split("\\*");
like image 179
squiguy Avatar answered Oct 12 '22 13:10

squiguy


Try this statement:

line.split("\\*");
like image 2
Aziz Shaikh Avatar answered Oct 12 '22 15:10

Aziz Shaikh


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("\\*");
like image 2
Cris_Towi Avatar answered Oct 12 '22 15:10

Cris_Towi