0

I have a bunch of strings that looks like this

/files/etc/hosts/2/ipaddr
/files/etc/hosts/2/canonical
/files/etc/hosts/2/alias[1]
/files/etc/hosts/3/ipaddr
/files/etc/hosts/3/canonical
/files/etc/hosts/3/alias[1]
/files/etc/hosts/4/ipaddr
/files/etc/hosts/4/canonical
/files/etc/hosts/4/alias[1]

I would like to append a 0 in front of any digit that sits between the / and /. After the append, the results should look like this...

/files/etc/hosts/02/ipaddr
/files/etc/hosts/02/canonical
/files/etc/hosts/02/alias[1]
/files/etc/hosts/03/ipaddr
/files/etc/hosts/03/canonical
/files/etc/hosts/03/alias[1]
/files/etc/hosts/04/ipaddr
/files/etc/hosts/04/canonical
/files/etc/hosts/04/alias[1]

I am pretty sure that I need to use a simple regular expression for searching. I think /\d*/ should be sufficient but I am not sure how to modify the string to insert the digit 0. Can someone give me some advice?

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
beyonddc
  • 1,246
  • 3
  • 13
  • 26
  • [See here](http://stackoverflow.com/a/13503345/2027196) for how to insert one string into another. Short answer - use StringBuilder. regex's aside, would that work? – JohnFilleau Jun 14 '13 at 14:34

1 Answers1

5

Use:

newString = string.replaceAll("/(\\d)(?=/)", "/0$1");

\\d is only one digit. Feel free to use \\d+ for one-or-more digits.

$1 means the part of the string that matched first thing that appears in brackets (with some exceptions), thus (\\d).

You need to use look-ahead (?=...) instead of just /(\\d)/ because otherwise

/files/etc/hosts/3/5/canonical

will become

/files/etc/hosts/03/5/canonical

instead of

/files/etc/hosts/03/05/canonical

(the / between 3 and 5 will get consumed during matching the 3 if you don't use look-ahead, thus it won't match on the 5).

This is not an issue (and you can simply use /(\\d)/) if the above string is not a possible input.

Java regex reference.

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138