C#正则表达式替换数字和单位

时间:2016-11-09 06:26:10

标签: c# regex string

有许多尺寸为。的产品名称。

例如" X 300g"," X 400 g"," X 250 kg"," X 25kg"。

现在我想替换" NumberUnit"的所有实例。使用" Number Unit",即" 300g"至" 300克"," 25千克"到" 25公斤"等等。

我知道我可以通过循环和字符串替换轻松地做到这一点,但是有数百万种产品,我担心这样做需要很长时间。

相反,我想在每个产品名称上做一个Regex.Replace()可能更好。

同意? - 你会怎么写正则表达式?

感谢。

2 个答案:

答案 0 :(得分:0)

Try this code:

(?<=\d)(?=[a-zA-Z])

The previous regex will capture the location between numbers and units only if they don't have a space in between. You can replace this location with a space, and you will be done.

Demo: https://regex101.com/r/yry7Sl/3

答案 1 :(得分:0)

试试这个:

    string pattern = @"(?<=\d)(?=[a-zA-Z])";
    string substitution = @" ";
    string input = @"""X 300g"", ""X 400 g"", ""X 250 kg"", ""X 25kg""";

    Regex regex = new Regex(pattern);
    string result = regex.Replace(input, substitution);