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
I was also wondering what regex I could use to get this. the words before the arrow are input and after is the output the text is in french. And right now I am using this it works but not with the apostrophe.
String [] tab = txaTexte.getText().split("(?:(?<![a-zA-Z])'|'(?![a-zA-Z])|[^a-zA-Z']) ")
Un beau JOUR. —> Un/beau/JOUR
La boîte crânienne —> La/boîte/crânienne
C’était mieux aujourd’hui —> C’/était/mieux/aujourd’hui
qu’autrefois —> qu’/autrefois
D’hier jusqu’à demain! —> D’/hier/jusqu’/à/demain
Dans mon sous-sol—> Dans/mon/sous-sol
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 hyphen0
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