Home > Software engineering >  Regex for negative number with leading zeros
Regex for negative number with leading zeros

Time:12-04

hey I need a regex that removes the leadings zeros. right now I am using this code . it does work it just doesn't keep the negative symbol.

String regex = "^ (?!$)";
String numbers = txaTexte.getText().replaceAll(regex, ")

after that I split numbers so it puts the numbers in a array.

input :
-0005
0003
-87

output :
-5
3
-87

CodePudding user response:

You might capture an optional hyphen, then match 1 more times a zero and 1 capture 1 or more digits in group 2 starting with a digit 1-9

^(-?)0 ([1-9]\d*)$
  • ^ Start of string
  • (-?) Capture group 1, match optional hyphen
  • 0 Match 0 zeroes
  • ([1-9]\d*) Capture group 2, match 1 digits starting with a digit 1-9
  • $ End of string

See a regex demo.

In the replacement use group 1 and group 2.

String regex = "^(-?)0 ([1-9]\\d*)$";
String text = "-0005";
String numbers = txaTexte.getText().replaceAll(regex, "$1$2");

CodePudding user response:

Here is one way. This preserves the sign.

  • capture the optional sign.
  • check for 0 or more leading zeros
  • followed by 1 or more digits.
String regex = "^([ -])?0*(\\d )";
String [] data = {"-1415", " 2924", "-0000123", "000322", " 000023"};
for (String num : data) {
    String after = num.replaceAll(regex, "$1$2");
    System.out.printf("%8s --> %s%n", num , after);
}

prints

   -1415 --> -1415
    2924 -->  2924
-0000123 --> -123
  000322 --> 322
  000023 -->  23
  • Related