我的字符串可以是" 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);
答案 0 :(得分:2)
如果您希望匹配字符串末尾的U
,2位数字,可选空格以及W
或M
的任何字符,请使用
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]
- W
或M
$
- 字符串结束。