get specific character

Viewed 64

I would like to remove Zero from a string, below is an example :

String a : 020200218-0PSS-0010

a.replaceall("-(?:.(?!-))+$", "**REPLACEMENT**")

Actual : 020200218-0PSS-0010 Expected : 020200218-0PSS-10

I'm using this regex to catch -0010 : -(?:.(?!-))+$

I just dont know what to do in the REPLACEMENT section to actually remove the unused zero (not the last zero for exemple "10" and not "1")

Thanks for reading!

3 Answers

You could use something like:

(?<=-)0+(?=[1-9]\d*$)

It translates to "find all zeros which come after a dash, leading up to a non-zero digit, followed by optional digits, till the end of the string."

The demo below is in PHP but it should be valid in Java as well.

https://regex101.com/r/7E2KKQ/1

$s.replaceAll("(?<=-)0+(?=[1-9]\d*$)", "")

This would also work:

(?<=-)(?=\d+$)0+

Find a position in which behind me is a dash and ahead of me is nothing but digits till the end of the line. From this position match one or more continuous zeros.

https://regex101.com/r/cdTjOz/1

You can try something like this:

String result = a.replaceAll("-0+(?=[1-9][0-9]*$)", "-");

For the input Sting: String a = "020200218-0PSS-00000010"; The output is: 020200218-0PSS-10

The pattern -(?:.(?!-))+$ matches a - and 1+ times any char asserting what is directly to the right is not -, until the end of the string.

This does not take any digits into account and if successful, will give a full match instead of the zeroes only.

Instead of lookarounds, you might also use a capturing group and use that group in the replacement with a - prepended.

-0+([1-9]\d*)$

Explanation

  • -0+ Match - and 1 or more times a zero
  • ( Capture group 1
    • [1-9]\d* Match a digit 1-9 followed by optional digits
  • ) Close group 1
  • $ Assert end of string

Regex demo | Java demo

As there is only 1 part to replace, you could use replaceFirst.

String a = "020200218-0PSS-0010";
String result = a.replaceFirst("-0+([1-9]\\d*)$", "-$1");
System.out.println(result);

Output

020200218-0PSS-10
Related