Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the effect of "*" in regular expressions?

Tags:

java

regex

My Java source code:

String result = "B123".replaceAll("B*","e");
System.out.println(result);

The output is:ee1e2e3e. Why?

like image 897
JSON Avatar asked Feb 03 '09 14:02

JSON


2 Answers

'*' means zero or more matches of the previous character. So each empty string will be replaced with an "e".

You probably want to use '+' instead:

replaceAll("B+", "e")

like image 80
Anders Westrup Avatar answered Oct 20 '22 00:10

Anders Westrup


You want this for your pattern:

B+

And your code would be:

String result = "B123".replaceAll("B+","e");
System.out.println(result);

The "*" matches "zero or more" - and "zero" includes the nothing that's before the B, as well as between all the other characters.

like image 40
Daniel Schaffer Avatar answered Oct 19 '22 23:10

Daniel Schaffer