简体   繁体   中英

Use C# to check is string contains an integer in a given range of numbers

I have a list of strings, some of which fall in the format "LAP1_...", "LAP2_...", ... , "LAP9_...". I want to count all the strings that follow the format "LAP" plus any integer 1-9. Is there a way to check if a string contains a substring that includes any integer in a given range?

I could obviously write the code like this:

 var lapCount = recentRecords.Where(x => x.nkFileName.Contains("LAP1")||x.nkFileName.Contains("LAP2") || x.nkFileName.Contains("LAP3")
            || x.nkFileName.Contains("LAP4") || x.nkFileName.Contains("LAP5") || x.nkFileName.Contains("LAP6") || x.nkFileName.Contains("LAP7")
            || x.nkFileName.Contains("LAP8") || x.nkFileName.Contains("LAP9")).Count();

but that seems unnecessarily long.

I would rather have the search look something like this:

 var lapCount = recentRecords.Where(x => x.nkFileName.Contains("LAP[1-9]")).Count();

You could use char.IsDigit https://docs.microsoft.com/de-de/dotnet/api/system.char.isdigit?view=netcore-3.1

string stringWithNumber = "sample 43 string 7 with number 42"; stringWithNumber.Any(char.IsDigit);

Reverse the test so it can be translated:

var lapCount = recentRecords.Where(r => r.nkFileName.StartsWith("LAP") && "0123456789".Contains(r.nkFileName.Substring(3,1))).Count();

You can try the following code snippet:

   List<string> strList = new List<string>()
    {
            "LAP1","ABC","explorer","LAP2","LAP3","xyz"
    };
    var myRegex=new Regex(@"LAP[0-9]");
    List<string> resultList=strList.Where(f => myRegex.IsMatch(f)).ToList();

The result would be:

结果

So In your case, I believe you can use:

var myRegex=new Regex(@"LAP[0-9]");   
List<string> resultList=recentRecords.Where(f => myRegex.IsMatch(f.nkFileName)).ToList();

Make sure that recentRecords is a list of strings.

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