views:

215

answers:

3

I'm trying to write a regex pattern that will find numbers with two leading 00's in it in a string and replace it with a single 0. The problem is that I want to ignore numbers in parentheses and I can't figure out how to do this.

For example, with the string:

Somewhere 001 (2009)

I want to return:

Somewhere 01 (2009)

I can search by using [00] to find the first 00, and replace with 0 but the problem is that (2009) becomes (209) which I don't want. I thought of just doing a replace on (209) with (2009) but the strings I'm trying to fix could have a valid (209) in it already.

Any help would be appreciated!

+2  A: 

Search one non digit (or start of line) followed by two zeros followed by one or more digits.

([^0-9]|^)00[0-9]+

What if the number has three leading zeros? How many zeros do you want it to have after the replacement? If you want to catch all leading zeros and replace them with just one:

([^0-9]|^)00+[0-9]+
Aviad P.
Thanks! With a minor correction, I got what I needed. I didn't think to use the space as part of the search. Guess it's too easy to miss the obvious. In case anyone needs it, the regex pattern I used to find the 00 is ([^0-9]|^)00.
Greg V
This wont ignore numbers in parentheses. It fails for "(0002)"
noah
You can ignore the space by use of the replacement tokens. To do this, you add an additional capture group. Here is the c# oneliner:yourString = Regex.Replace(yourString, "([^0-9]|^)00+([0-9]+)", "$10$2");
tyshock
A: 
?Regex.Replace("Somewhere 001 (2009)", " 00([0-9]+) ", " 0$1 ")
"Somewhere 01 (2009)"
serhio
+1  A: 

Ideally, you'd use negative look behind, but your regex engine may not support it. Here is what I would do in JavaScript:

string.replace(/(^|[^(\d])00+/g,"$10");

That will replace any string of zeros that is not preceded by parenthesis or another digit. Change the character class to [^(\d.] if you're also working with decimal numbers.

noah
This is the cleanest approach.
tyshock