简体   繁体   中英

C# Regex.Replace number letter number

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"

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 "

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM