DevelopingDeveloper
DevelopingDeveloper

Reputation: 913

Regex to remove character from within a string after alphabetic characters

I have a string of characters, String a = "abcd000324";

I would like to remove the 0's from the string using a regex to result in the string abcd324

Is there a regex value to replace a certain character (i.e. 0) after alphabetic characters but not remove the 324. It would also need to work in the case of the number appearing later in the string, i.e. abcd0034505 should result to abcd34505

Upvotes: 0

Views: 179

Answers (2)

Mad Physicist
Mad Physicist

Reputation: 114330

To avoid having to replace parts of the regex back into itself, use positive lookbehind ((?<=...)):

(?<=\D)0+

This will match a sequence of zeros only if they are preceded by some non-digit character. You can now do

str.replaceFirst("(?<=\\D)0+", "")

without having to pass any references to capture groups.

Link to Regex101 example.

Upvotes: 2

anubhava
anubhava

Reputation: 785246

Yo can search using this regex:

^(\D*)0+

And replace it by using "$1" which is back-reference of first group which is \D* i.e. 0 or more non-digit characters.

RegEx Demo

Java code:

String repl = input.replaceFirst("^(\D*)0+", "$1");

Upvotes: 3

Related Questions