简体   繁体   English

如何匹配数组中包含的字符串中的字符串模式

[英]How to match a string pattern in a string contained in array

I need to check if a string pattern in the array is contained in a string. 我需要检查字符串中是否包含数组中的字符串模式。 I am using the following code but it matches the exact string contained in the array not the pattern so the following will fail. 我正在使用以下代码,但它与数组中包含的确切字符串而不是模式匹配,因此以下操作将失败。 How can I do this? 我怎样才能做到这一点?

String[] stringArrayToBlock = { "#", "/", "string1:", "string2" };
String SearchString = "String1:sdfsfsdf";

 if (stringArrayToBlock.Contains(SearchString.Trim().ToLower()))
 { 
   //Do work
 }

I guess you should do it vice versa. 我想你应该反之亦然。 Besides, if you're open to LINQ, Enumerable.Any Method is very handy: 此外,如果您愿意使用LINQ,则Enumerable.Any方法非常方便:

string[] stringArrayToBlock = { "#", "/", "string1:", "string2" };
string SearchString = "String1:sdfsfsdf";
string lowerCaseString = SearchString.Trim().ToLower();
if (stringArrayToBlock.Any(s => lowerCaseString.Contains(s)))    
{
    //Do work
}

Use the LINQ Any() method to determine if any of the elements of the array satisfy the condition. 使用LINQ Any()方法来确定数组的任何元素是否满足条件。 The Contains method used here is that of string , not of Array . 这里使用的Contains方法是string ,而不是Array

String[] stringArrayToBlock = { "#", "/", "string1:", "string2" };
String SearchString = "String1:sdfsfsdf";

 if (stringArrayToBlock.Any(s => SearchString.Trim().ToLower().Contains(s)))
 { 
     //Do work
 }

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

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