0

i have contact number which i am getting from parameter which is of type String.

 String pharmacyPhone = "123456789";

here i want to add - after every 3rd digit and before 4th digit

so the output will become like pharmacyPhone = 123-456-789.

so how to achieve this?

flyingfox
  • 13,414
  • 3
  • 24
  • 39
Lalit Dubey
  • 51
  • 1
  • 9

1 Answers1

3

One approach uses a regex replacement:

String pharmacyPhone = "123456789";
pharmacyPhone = pharmacyPhone.replaceAll("(.{3})(?=.)", "$1-");
System.out.print(pharmacyPhone);

123-456-789

The pattern (.{3})(?=.) works by matching and capturing three digits at a time, provided that there is at least one more digit which follows. It then replaces with those captured three digits followed by a dash. The positive lookahead (?=.) ensures that we don't add a dash at the end of the string.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360