Is it possible to replace leading zeros in a string with an equal number of spaces using replaceAll ()?
In Java, I'm trying to replace strings like "001.234" with "spacespace1.234". However, I am a regex noob and I seem to end up with all leading zeros replaced with a single space.
I understand that I can do this easily with a loop, but I am trying to match regexes and appreciate any help :)
+3
source to share
2 answers
No problems:
String resultString = subjectString.replaceAll("\\G0", " ");
\G
acts like \A
(start of line anchor) on the first iteration replaceAll()
, but on subsequent passes, it ties the match to where the previous match ended. This prevents zeros from being matched elsewhere in the string, such as after the decimal point.
+6
source to share