简体   繁体   中英

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

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.

\\\\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.

[\\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

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