简体   繁体   English

正则表达式模式可过滤掉所有不匹配的内容

[英]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. 使用Regex.Replace(mystring, @"[^MV:0-9]", "")将除去未任何信件MV: ,或(也可以使用\\ d)0-9的问题是我想删除不是MV:然后删除数字。

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: 如果我选择了Latter选项,那么将没有:

        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: ) (它将始终以MV:之后的数字开头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. 那应该给您确切您需要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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