Reputation: 227
I'm currently trying to perform an array search which will return true if the array contains a string matches specific characters.
For example:
I have an array that contains these 3 values
"Atlanta Hawks are great this year!",
"Atlanta Braves are okay this year!",
"Atlanta Falcons are great this year!"
What I'm looking to do is to return true if the array contains at least one value matching the needle below...
"Atlanta* *are great this year!"
(Decided to use an asterisk as a wildcard in this example)
Which in this case would return true.
However for this array
"Atlanta Hawks are bad this year!",
"Detroit Tigers are okay this year!",
"New England Patriots are good this year!"
It would return false.
Currently what I'm doing is.. (and not working)
if (result.Properties["memberOf"].Matches("Atlanta* *are great this year!"))
{
return true;
}
My question is, are there any wildcards that can be used with the .Contains() method or is there a similar method to the preg_grep() in PHP in C#?
I appreciate your help in advance.
Upvotes: 3
Views: 21235
Reputation: 186678
I suggest converting wild card (with *
and ?
) into a regular expression pattern and then using Linq to find out if there's Any
item that matches the regular expression:
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));
You may want to wrap the implementation into a method:
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!");
Upvotes: 3
Reputation: 1
Don't have a compiler at hand, but it should be something like this:
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;
}
Upvotes: 0
Reputation: 3349
You can do it like this:
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;
}
}
Upvotes: 1