-3

Hi, first of all this is my first question here. Pls understand if any mistakes are there.

I am new to regular expression. I am having the range of numbers 1–65535.

If numbers are coming in sequence like 1, 2, 3, 4…65535 I need to put padding of zeros at start to make them all in same length (fixed 5 digit length).

Output should be like (just add padding of zeros to make fix length):

00001
00002
…
01245
78657

I know we can use string.format function in Java.

String.format("%05d", str);

Pls, Don't evaluate above from syntax pov.

I am strongly looking for regex for the solution. Because the regex implementation is provided to support and will not impact my code. It will be great if explanation is also provided.

Thanks for supporting.

Raj
  • 7
  • 1
  • 2
    You have an [XY problem](https://en.wikipedia.org/wiki/XY_problem): You're demanding a "regex" solution when regex is useless for the task and there exists a standard solution. Show us your `format()` solution and describe how it's falling short. – Bohemian Jun 03 '22 at 09:46
  • 1
    Out of curiosity, why do you want to use a regex here? `String.format` sounds like the most appropriate tool. – ndc85430 Jun 03 '22 at 09:46
  • 3
    `String example = "x = 42, y = 100, z = 12345"; String result = Pattern.compile("\\b[0-9]{1,4}\\b").matcher(example) .replaceAll(mr -> "0".repeat(5 - mr.end() + mr.start()) + mr.group());` – Holger Jun 03 '22 at 09:46
  • @Bohemian i am not in xy problem. I already told the solution using format ,but i need using regex if you have any suggestions for solution or actual one only put the comments.I am new to writing questions that's what you might be understood wrong or something. – Raj Jun 04 '22 at 11:09

1 Answers1

0
String sN = String.format("%05d",n);

The others have said all there is to say about XY problems and formatting and the inappropriateness of regex

g00se
  • 1,623
  • 1
  • 2
  • 6