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


You can replace

public static void main(String[] args) {
        String before = "00000001.234";

        String after = before.replaceAll("0", " ");

        System.out.println("This is after :"+after+" replacing");
    }

      



Output: This is after : 1.234 replacing

0


source







All Articles