简体   繁体   English

带有[\\ d] *的String.replaceAll()在字符之间附加替换字符串,为什么?

[英]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. 我相信[0-9] *或[\\ d] *应该是我想要的,当我使用Java的String.replaceAll时,它将我的替换字符串添加到不应该与正则表达式匹配的位置。

For example: I have an input string of "This is my99String problem" If my replacement string is "~" 例如:我有一个输入字符串“这是my99String问题”如果我的替换字符串是“〜”

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~" 我的返回字符串是“~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 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. 我做错了什么,为什么java匹配这样。

\\\\d* matches 0 or more digits, and so it even matches an empty string. \\\\d*匹配0位或更多位数,因此它甚至匹配空字符串。 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. 请尝试使用\\\\d+ And you don't need to include \\\\d in character class. 而且您不需要在字符类中包含\\\\d

[\\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. 这将匹配1个或更多数字。

From the doc : 来自doc

Greedy quantifiers
X?  X, once or not at all
X*  X, zero or more times
X+  X, one or more times

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM