Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.replaceAll() with [\d]* appends replacement String inbetween characters, why?

Tags:

java

regex

I have been trying for hours now to get a regex statement that will match an unknown quantity of consecutive numbers. I believe [0-9]* or [\d]* should be what I want yet when I use Java's String.replaceAll it adds my replacement string in places that shouldn't be matching the regex.

For example: I have an input string of "This is my99String problem" If my replacement string is "~"

When I run this

myString.replaceAll("[\\d]*", "~" )

or

myString.replaceAll("[0-9]*", "~" )

my return string is "~T~h~i~s~ ~i~s~ ~m~y~~S~t~r~i~n~g~ ~p~r~o~b~l~e~m~"

As you can see the numbers have been replaced but why is it also appending my replacement string in between characters.

I want it to look like "This is my~String problem"

What am I doing wrong and why is java matching like this.

like image 479
jon.mervine Avatar asked Dec 05 '25 03:12

jon.mervine


2 Answers

\\d* matches 0 or more digits, and so it even matches an empty string. And you have an empty string before every character in your string. So, for each of them, it replaces it with ~, hence the result.

Try using \\d+ instead. And you don't need to include \\d in character class.

like image 108
Rohit Jain Avatar answered Dec 06 '25 17:12

Rohit Jain


[\\d]*

matches zero or more (as defined by *). Hence you're getting matches all through your strings. If you use

[\\d]+

that'll match 1 or more numbers.

From the doc:

Greedy quantifiers
X?  X, once or not at all
X*  X, zero or more times
X+  X, one or more times
like image 32
Brian Agnew Avatar answered Dec 06 '25 16:12

Brian Agnew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!