正则表达式匹配并替换为模式

时间:2018-06-15 23:57:55

标签: c# regex

我的字符串可以是" Wings U15 W" " Wings U15W" " Wings U15M" " Wings U15 M" 我希望输出为" Wings U15" my代码如下。

string _Input = "Wings U15 W";

if (Regex.Match(_Input, " U[0-9]{2} (W|M)").Success)
{
    string pattern = "U[0-9]{2} (W|M)";
    string replacement = "";
    _Input = Regex.Replace(_Input, pattern, replacement);

}

MessageBox.Show(_Input);

1 个答案:

答案 0 :(得分:2)

如果您希望匹配字符串末尾的U,2位数字,可选空格以及WM的任何字符,请使用

var m = Regex.Match(_Input, @"^(.* U[0-9]{2}) ?[WM]$");
var result = "";
if (m.Success) 
{
    result = m.Groups[1].Value;
}

请参阅regex demo

模式详情

  • ^ - 字符串开头
  • (.* U[0-9]{2}) - 第1组:
    • .* - 除LF符号以外的任何0 +字符,尽可能多(如果您计划匹配任何1个字母字符(字母,数字或\w+,请替换为_ ))
    • - 一个空格(替换为\s以匹配任何空格)
    • U - U
    • [0-9]{2} - 2位数
  • ? - 一个可选空格(替换为\s?以匹配任何1或0个空格字符)
  • [WM] - WM
  • $ - 字符串结束。