c# .contains()使用正则表达式
本文关键字:正则表达式 contains | 更新日期: 2023-09-27 18:15:58
我目前正在尝试执行数组搜索,如果数组包含字符串匹配特定字符,将返回true。
例如:我有一个包含这三个值的数组
"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()方法?
提前感谢您的帮助。
我建议将通配符 (*
和?
)转换为正则表达式模式,然后使用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!");
你可以这样做:
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;
}
}
手头没有编译器,但应该是这样的:
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;
}