How do I replace the string
2X6X14 #2&BTR KD SPF MIRREX 1/2X5
with
2 x 6 x 14 #2&BTR KD SPF MIRREX 1/2 x 5
I want to replace "X" with " x " but only if it is surrounded by numbers, not if it is eg on the end of a word like MIRREX
CodePudding user response:
An X with a digit either side:
var output = Regex.Replace(input, @"(\d)X(?=\d)", "$1 x ");
This finds a digit followed by X, followed by another digit. It captures the first digit into a group $1 that is used in the replacement of eg 2X -> 2 x then moves into the next match
Or indeed as Cary commented (with the small typo of X/x), just using lookarounds:
var output = Regex.Replace(input, @"(?<=\d)X(?=\d)", " x ");
..similar idea - finds an X between two digits, neither of which are captured or prevent matching the next X, so it's a case of replacing the found X with " x "
