Southsouth
Southsouth

Reputation: 2695

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

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.

Upvotes: 7

Views: 9832

Answers (3)

Bakri Bitar
Bakri Bitar

Reputation: 1697

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

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

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.

Upvotes: 1

jdweng
jdweng

Reputation: 34433

Use Regex

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            string prefix = "abc";
            string suffix = "xyz";
            string pattern = string.Format("{0}.*{1}", prefix, suffix);

            string input = "abc123456789xyz";

            bool resutls = Regex.IsMatch(input, pattern);
        }
    }
}
​

Upvotes: 0

Related Questions