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?
You can do it by replacing 0's with space using matchevaluator!
Regex.Replace("685774010M00555P002",
@"^(?<Bestellnr>\w{6})(?<Pos>\d{3})M(?<Menge>\d{5})P(?<Lfd>\d{3})$",
m=>m.Groups["Bestellnr"].Value+""+
Regex.Replace(m.Groups["Pos"].Value,"(?<=^0*)0"," ")+
" "+
Regex.Replace(m.Groups["Lfd"].Value,"(?<=^0*)0"," "));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With