Frederic Henri
Frederic Henri

Reputation: 53713

Regex to exclude trailing zero with even numbers of digits

I need some support on a regex I am trying to write.

I received a string which is always made of 8 digits (like 12345678). From this string, I need to remove trailing zeros but always keeping an even number of digits.

So for example:

The though part for me is to make sure to keep the even numbers.

I tried using some (\d\d)+[^(00)]+ but it does not achieve what I want.

Upvotes: 1

Views: 355

Answers (3)

Amit Kumar Lal
Amit Kumar Lal

Reputation: 5789

import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "(00)*$";
final String string = "12345678\n"
     + "12400000\n"
     + "12005600\n"
     + "12340000\n"
     + "12000000\n"
     + "12340000\n"
     + "12345000";
final String subst = "";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);

System.out.println("Substitution result: " + result);

Below is the result

Substitution result: 12345678
1240
120056
1234
12
1234
123450

Upvotes: 0

Sweeper
Sweeper

Reputation: 271185

A simple regex like this should work:

(?:00)+$

replace with empty string.

I used a non-capturing group instead of character class to group 2 zeros together, and then added a + quantifier to only match "multiples" of 2 zeros i.e. an even number of zeros.

Demo

If you want a regex that can match instead of replace, this works:

^\d+?0?(?=(?:00)*$)

Lazily looking for digits until we reach a 0. Do we match this zero or not? That depends on whether we see an even number of 0s after it. This however does not work with the case of all 0s, like 0000, but since you said that you will never encounter this value, you don't need to worry too much.

Demo

Upvotes: 5

Gurmanjot Singh
Gurmanjot Singh

Reputation: 10360

Try this regex:

(?:00)*$

Replace each match with a blank string.

click for Demo

Explanation:

  • (?:00)* - matches 0 or more occurrences of 00.
  • $ - asserts the end of the line.

Upvotes: 5

Related Questions