Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string contains substring with wildcard? like abc*xyz

Tags:

c#

When I parse lines in text file, I want to check if a line contains abc*xyz, where * is a wildcard. abc*xyz is a user input format.

like image 490
Southsouth Avatar asked Jul 18 '15 11:07

Southsouth


Video Answer


2 Answers

You can generate Regex and match using it

 searchPattern = "abc*xyz";

 inputText = "SomeTextAndabc*xyz";

 public bool Contains(string searchPattern,string inputText)
  {
    string regexText = WildcardToRegex(searchPattern);
    Regex regex = new Regex(regexText , RegexOptions.IgnoreCase);

    if (regex.IsMatch(inputText ))
    {
        return true;
    }
        return false;
 }

public static string WildcardToRegex(string pattern)
{
    return "^" + Regex.Escape(pattern)
                      .Replace(@"\*", ".*")
                      .Replace(@"\?", ".")
               + "$";
}

Here is the source and Here is a similar issue

like image 121
Bakri Bitar Avatar answered Oct 29 '22 16:10

Bakri Bitar


If asterisk is the only wildcard character that you wish to allow, you could replace all asterisks with .*?, and use regular expressions:

var filter = "[quick*jumps*lazy dog]";
var parts = filter.Split('*').Select(s => Regex.Escape(s)).ToArray();
var regex = string.Join(".*?", parts);

This produces \[quick.*?jumps.*?lazy\ dog] regex, suitable for matching inputs.

Demo.

like image 43
Sergey Kalinichenko Avatar answered Oct 29 '22 16:10

Sergey Kalinichenko