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.
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!");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With