I’m using a regular expression replace (in a .Net application) to create an item id from a barcode. Here’s the regex I’m using:
^(?<Bestellnr>\w{6})(?<Pos>\d{3})M(?<Menge>\d{5})P(?<Lfd>\d{3})$
The replacement string is (it has leading blanks, but that’s not important here):
${Bestellnr}${Pos} ${Lfd}
An example input would be:
685774010M00555P002
The current result of the above replacement is:
685774010 002
But now my customer wants me to remove the leading zeroes from the groups “Pos” and “Lfd”, so the result should change to:
685774 10 2
Edit: Please note that the two zeroes in the “lfd” group are replaced by two blanks!
I’ve tried for hours now, but I cannot seem to get this working. Best approach I was able to find was to create extra groups for the leading zeroes like:
^(?<Bestellnr>\w{6})(?<PosNull>0*)(?<Pos>\d{1,})M(?<Menge>\d{5})P(?<LfdNull>0*)(?<Lfd>\d{1,})$
But I don’t know how I can replace the “null groups” with the correct number of blanks. Is this possible at all? (Until now I thought there’s nothing that’s not possible with Regex 😉
Can anyone help?
Ok, found a solution that fits my needs. It’s done with a simple String.Format, passing it the Groups of the Regex converted to ints. Groups are accessed by index, but since it’s done in the format string, no hardcoding is required.
Here’s the code:
Remarks: