我目前正在尝试执行数组搜索,如果数组包含与特定字符匹配的字符串,则返回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()类似的方法?
我提前感谢您的帮助。
答案 0 :(得分:0)
你可以这样做:
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;
}
}
答案 1 :(得分:0)
手头没有编译器,但它应该是这样的:
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;
}
答案 2 :(得分:0)
我建议将外卡(包含*
和?
)转换为正则表达式模式,然后使用 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));
您可能希望将实现包装到方法中:
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!");