Reputation: 1266
My string can be "Wings U15 W" or "Wings U15W" or "Wings U15M" or "Wings U15 M" I would like to get output as "Wings U15" my code as below.
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);
Upvotes: 0
Views: 101
Reputation: 626691
If you want to match any chars up to U
, 2 digits, an optional space and W
or M
at the end of the string, use
var m = Regex.Match(_Input, @"^(.* U[0-9]{2}) ?[WM]$");
var result = "";
if (m.Success)
{
result = m.Groups[1].Value;
}
See the regex demo
Pattern details
^
- start of string(.* U[0-9]{2})
- Group 1:
.*
- any 0+ chars other than LF symbol, as many as possible (replace with \w+
if you plan to match any 1+ word chars (letters, digits or _
))
- a space (replace with \s
to match any whitespace)U
- an U
[0-9]{2}
- 2 digits ?
- an optional space (replace with \s?
to match any 1 or 0 whitespace chars)[WM]
- W
or M
$
- end of string.Upvotes: 2