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

When I parse lines in a text file, I want to check if the line contains abc*xyzwhere it *is a wildcard. abc*xyzis the user input format.

+4
source share
3 answers

If the asterisk is the only wildcard that you want to allow, you can replace all the 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 creates a regular expression \[quick.*?jumps.*?lazy\ dog]suitable for matching inputs.

Demo version

0
source

You can generate Regexand use 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(@"\?", ".")
               + "$";
}

+1

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);
        }
    }
}
0
source

Source: https://habr.com/ru/post/1598505/


All Articles