简体   繁体   English

使用 C# 检查字符串是否在给定的数字范围内包含 integer

[英]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_...".我有一个字符串列表,其中一些格式为“LAP1_...”、“LAP2_...”、...、“LAP9_...”。 I want to count all the strings that follow the format "LAP" plus any integer 1-9.我想计算所有遵循“LAP”格式的字符串加上任何 integer 1-9。 Is there a way to check if a string contains a substring that includes any integer in a given range?有没有办法检查一个字符串是否包含一个 substring 包含给定范围内的任何 integer ?

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您可以使用 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"; string stringWithNumber = "样本 43 字符串 7,编号为 42"; stringWithNumber.Any(char.IsDigit); 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.确保recentRecords是一个字符串列表。

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

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