AllenG
AllenG

Reputation: 8190

Regex question: Why isn't this matching?

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?

Upvotes: 1

Views: 198

Answers (2)

Simon Chadwick
Simon Chadwick

Reputation: 1148

Try this:

(?<=\.\d+?)0*?(?=\D|$)

Upvotes: 0

Konrad Rudolph
Konrad Rudolph

Reputation: 545598

+? 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.

Upvotes: 2

Related Questions