tags:

views:

63

answers:

2

I have the following regex: (?<=\.\d+?)0+(?=\D|$) I'm running it against a string which contains the following: SVC~NU^0270~313.3~329.18~~10~~6.00:

When it runs, it matches the 6.00 (correctly) which my logic then trims by one zero to turn into 6.0. The regex then runs again (or should) but fails to pick up the 6.0.

I'm by no means an expert on Regex, but my understanding of my expression is that it's looking for a decimal with 1 or more optional (so, really zero or more) digits prior to one or more zeros which are then followed by any non-digit character or the line break. Assuming that interpretation is correct, I can't see why it wouldn't match on the second pass. For that matter, I'm not sure why my Regex.Replace isn't matching the full 6.00 on the first pass and removing both of the trailing zeros...

Any suggestions?

+2  A: 

+? means “match one or more, non-greedy”. You presumably think that it means the same as *, i.e. match zero or more times. So the preceding expression \d must match at least once for your whole expression to match, and that’s no longer the case for the input 6.0.

Change +? to * and the expression should work.

Konrad Rudolph
I just tried that, that will strip out any Zeros full stop... therefore `SVC~NU^0270~313.3~329.18~~10~~6.00000000000:` would become `SVC~NU^0270~313.3~329.18~~10~~6.:`
Glycerine
@Glycerine: Yup, this would change the meaning of the regular expression. Isn’t that what the OP wants? After all, he explicitly *does* want to find `6.0` and strip out the trailing zero.
Konrad Rudolph
Which means that your regex only matches if there are at least two digits after the decimal, and if the last (one-or-more) digits are zero. It will never match a zero directly after the decimal point.I think you just need to replace `\d+?` with `\d*`
@adam-boyers: Uh? That’s exactly what I’m suggesting. Did you perhaps misread something?
Konrad Rudolph
A: 

Try this:

(?<=\.\d+?)0*?(?=\D|$)
Simon Chadwick
Notice that this may result in a match of size zero (if there is such a thing in .NET …).
Konrad Rudolph
This change merely allows it to match an empty string when the sequence *doesn't* end with zeroes--and yes, @Konrad, that's perfectly legal. But it's pointless in this case, since the intent is to remove the trailing zeroes.
Alan Moore