简体   繁体   中英

Regex Pattern for filter out anything that doesn't Match

Using Regex.Replace(mystring, @"[^MV:0-9]", "") will remove any Letters that are not M , V , : , or 0-9 (\\d could also be used) the problem is I want to remove anything that is not MV: then numbers.

I need to replace anything that is not this pattern with nothing:

Starting String                        | Wanted Result
---------------------------------------------------------
sdhfuiosdhusdhMV:1234567890sdfahuosdho | MV:1234567890
MV:2138911230989hdsafh89ash32893h8u098 | MV:2138911230989
809308ej0efj0934jf0934jf4fj84j8904jf09 | Null
123MV:1234321234mnnnio234324234njiojh3 | MV:1234321234
mdfmsdfuiovvvajio123oij213432ofjoi32mm | Null

But what I get with what I have is:

Starting String                        | Returned Result
---------------------------------------------------------
sdhfuiosdhusdhMV:1234567890sdfahuosdho | MV:1234567890
MV:2138911230989hdsafh89ash32893h8u098 | MV:213891123098989328938098
809308ej0efj0934jf0934jf4fj84j8904jf09 | 809308009340934484890409
123MV:1234321234mnnnio234324234njiojh3 | 123MV:12343212342343242343
mdfmsdfuiovvvajio123oij213432ofjoi32mm | mmvvv1232134232mm

And even if there is a Regex pattern for this would I be better off using something along the lines of:

if (Regex.IsMatch(strMyString, @"MV:"))
{
    string[] strarMyString = Regex.Split(strMyString, @"MV:");
    string[] strarNumbersAfterMV = Regex.Split(strarMyString[1], @"[^\d]");
    string WhatIWant = strarNumbersAfterMV[0]
}

If I went with the Latter option would there be away to have:

        string[] strarNumbersAfterMV = Regex.Split(strarMyString[1], @"[^\d]");

Only make one split at the first change from numbers? (It will always start with number following the MV: )

Can't you just do:

string matchedText = null;
var match = Regex.Match(myString, @"MV:[0-9]+");
if (match.Success)
{
    matchedText = Value;
}
Console.WriteLine((matchedText == null) ? "Not found" : matchedText);

That should give you exactly what you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM