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.
Asked
Active
Viewed 8,744 times
7

Sergey Kalinichenko
- 714,442
- 84
- 1,110
- 1,523

Southsouth
- 2,659
- 6
- 32
- 39
-
1Very cool, good luck! – moffeltje Jul 18 '15 at 11:50
3 Answers
3
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(@"\?", ".")
+ "$";
}

Community
- 1
- 1

Bakri Bitar
- 1,543
- 18
- 29
-
Note that you can edit the mehod WildcardToRegex to control the output regex... for example remove the "^" which is used to force the regex to match from the beginning of the input or remove the "$" which does the same but for the end of input – Bakri Bitar Jul 18 '15 at 12:07
1
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.

Sergey Kalinichenko
- 714,442
- 84
- 1,110
- 1,523
-
To be able to escape the wildcard itself, you can use escaped splitting like here: https://rosettacode.org/wiki/Tokenize_a_string_with_escaping#C.23 – Niklas Peter Aug 25 '18 at 11:18
0
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);
}
}
}

jdweng
- 33,250
- 2
- 15
- 20