0

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);

1 Answer 1

2

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.
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much. And how can I add more options to [WM] for Wings U15 MU or Wings U15 WU?
@Kerberos To match MU or WU use [MW]U. If U is optional, add ? after it.
Thank you again. This is very useful. I arranged as @"^(.* U[0-9]{2}) ?[WM]?U$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.