regex C# .contains()使用正则表达式

mjqavswn  于 2023-05-19  发布在  C#
关注(0)|答案(3)|浏览(221)

我目前正在尝试执行一个数组搜索,如果数组包含一个匹配特定字符的字符串,则返回true。
例如:
我有一个包含这3个值的数组

"Atlanta Hawks are great this year!",
"Atlanta Braves are okay this year!",
"Atlanta Falcons are great this year!"

我想做的是返回true,如果数组包含至少一个值匹配下面的指针…

"Atlanta* *are great this year!"

(决定在本例中使用星号作为通配符)
在本例中返回true。
但是对于这个数组

"Atlanta Hawks are bad this year!",
"Detroit Tigers are okay this year!",
"New England Patriots are good this year!"

它将返回false。
我现在做的是...(不工作)

if (result.Properties["memberOf"].Matches("Atlanta* *are great this year!"))
                {
                    return true;
                }

我的问题是,是否有通配符可以与.Contains()方法一起使用,或者是否有类似于C#中PHP中preg_grep()的方法?
我很感激你的帮助提前。

f2uvfpb9

f2uvfpb91#

我建议将 * wildcard *(带有*?)转换为 regular expression 模式,然后使用 Linq 来查找是否有Any项与正则表达式匹配:

string[] data = new string[] {
    "Atlanta Hawks are great this year!",
    "Atlanta Braves are okay this year!",
    "Atlanta Falcons are great this year!"
  };

  string wildCard = "Atlanta* *are great this year!";

  // * - match any symbol any times
  // ? - match any symbol just once
  string pattern = Regex.Escape(wildCard).Replace(@"\*", ".*").Replace(@"\?", ".");

  bool result = data.Any(item => Regex.IsMatch(item, pattern));

您可能希望将实现 Package 到一个方法中:

private static bool ContainsWildCard(IEnumerable<String> data, String wildCard) {  
    string pattern = Regex.Escape(wildCard).Replace(@"\*", ".*").Replace(@"\?", ".");

    return data.Any(item => Regex.IsMatch(item, pattern));
  }

  ...

  String[] test = new String[] {
    "Atlanta Hawks are bad this year!",
    "Detroit Tigers are okay this year!",
    "New England Patriots are good this year!"
  }

  bool result = ContainsWildCard(test, "Atlanta* *are great this year!");
rdrgkggo

rdrgkggo2#

你可以这样做:

string[] input = {"Atlanta Hawks are great this year!", "Atlanta Braves are okay this year!", "Atlanta Falcons are great this year!"};
var output = false;
Regex reg = new Regex("Atlanta (.*) are great this year!");
foreach (var item in input)
{        
    Match match = reg.Match(item);
    if (match.Success)
    {
        output = true;
        break;
    }
}
hwamh0ep

hwamh0ep3#

手头没有编译器,但它应该是这样的:

public boolean checkMyArray(string[] theStringArray) {
    string pattern = "Atlanta (.*) are (great|okay) this year!";
    foreach (string s in theStringArray) {
       if(System.Text.RegularExpressions.Regex.IsMatch(s, pattern))
          return true;
    }
    return false;
}

相关问题