1

I have tried to find a method in c# to return a string of a wildcard match, however I can only find information on how to return if it contains the wildcard match, not the string the wildcard match represents.

For example,

var myString = "abcde werrty qweert";
var newStr = MyMatchFunction("a*e", myString);
//myString = "abcde"

How would I create MyMatchFunction? I have searched around on stackoverflow, but everything that has to do with c# and wildcard is just returning boolean values on if the string contains the wildcard string, and not the string it represents.

jayjay93
  • 553
  • 1
  • 7
  • 14
  • Possible duplicate of [Splitting a string in C#](https://stackoverflow.com/questions/15421651/splitting-a-string-in-c-sharp) – Rudresha Parameshappa Jun 05 '18 at 19:36
  • 1
    Possible duplicate of [Matching strings with wildcard](https://stackoverflow.com/questions/30299671/matching-strings-with-wildcard) – Xiaoy312 Jun 05 '18 at 19:40

2 Answers2

3

Have you considered using Regex?

For instance, with the pattern a.*?e, you could achieve this effect

string sample  = "abcde werrty qweert";
string pattern = "a.*?e";
Regex rgx      = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection matches = rgx.Matches(sample);

foreach (Match match in matches)
    Console.WriteLine(match.Value);

Which would print out

abcde
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
N.D.C.
  • 1,601
  • 10
  • 13
0

Default of wildcard search for "abcde werrty qweert" with pattern of "a*b" will returns "abcde werrty qwee", but you can use gready search for the result of "abcde".

Function for WildCard match using Regex:

public static string WildCardMatch(string wildcardPattern, string input, bool Greedy = false)
{
    string regexPattern = wildcardPattern.Replace("?", ".").Replace("*", Greedy ? ".*?" : ".*");
    System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(input, regexPattern, 
        System.Text.RegularExpressions.RegexOptions.IgnoreCase);
    return m.Success ? m.Value : String.Empty;
}

Result:

var myString = "abcde werrty qweert";

var newStr = WildCardMatch("a*e", myString);
//newStr = "abcde werrty qwee"

newStr = WildCardMatch("a*e", myString, Greedy: true);
//newStr = "abcde"
Hossein Golshani
  • 1,847
  • 5
  • 16
  • 27