The87Boy
The87Boy

Reputation: 887

Replace all characters and first 0's (zeroes)

I am trying to replace all characters inside a Regular Expression expect the number, but the number should not start with 0
How can I achieve this using Regular Expression?

I have tried multiple things like @"^([1-9]+)(0+)(\d*)"and "(?<=[1-9])0+", but those does not work

Some examples of the text could be hej:\\\\0.0.0.22, hej:22, hej:\\\\?022 and hej:\\\\?22, and the result should in all places be 22

Upvotes: 0

Views: 940

Answers (4)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112447

According to one of your comments hej:\\\\0.011.0.022 should yield 110022. First select the relevant string part from the first non zero digit up to the last number not being zero:

([1-9].*[1-9]\d*)|[1-9]

[1-9]       is the first non zero digit
.*             are any number of any characters
[1-9]\d* are numbers, starting at the first non-zero digit
|[1-9]     includes cases consisting of only one single non zero digit

Then remove all non digits (\D)

Match match = Regex.Match(input, @"([1-9].*[1-9]\d*)|[1-9]");
if (match.Success) {
    result = Regex.Replace(match.Value, "\D", "");
} else {
    result = "";
}

Upvotes: 1

MethodMan
MethodMan

Reputation: 18843

Here is something that you can try The87Boy you can play around with or add to the pattern as you like.

string strTargetString = @"hej:\\\\*?0222\";
string pattern = "[\\\\hej:0.?*]";
string replacement = " ";

Regex regEx = new Regex(pattern);
string newRegStr = Regex.Replace(regEx.Replace(strTargetString, replacement), @"\s+", " ");

Result from the about Example = 22

Upvotes: 0

El Ronnoco
El Ronnoco

Reputation: 11922

Use following

[1-9][0-9]*$

You don't need to do any recursion, just match that.

Upvotes: 0

fge
fge

Reputation: 121750

Rather than replace, try and match against [1-9][0-9]*$ on your string. Grab the matched text.

Note that as .NET regexes match Unicode number characters if you use \d, here the regex restricts what is matched to a simple character class instead.

(note: regex assumes matches at end of line only)

Upvotes: 1

Related Questions