The value for input 2
can be a valid regular expression. All you need to do would be to add the ^
and $
anchors, these will allow your regex engine to specifically match that pattern, so in your case, you could do something like so:
String input2 = "file*.xml";
Regex regex = new Regex("^" + input2.Replace(".", "\\.").Replace("*",".*") + "$");
String input1 = "file_123.xml";
String input3 = "file_123.xml.done";
System.Console.WriteLine(regex.IsMatch(input1));
System.Console.WriteLine(regex.IsMatch(input3));
System.Console.ReadLine();
...
The .
is a special character in regex so it needs to be escaped. The second replace
statement adds a .
which means any character infront of the *
operator which means or or more repetitions of. The code above yields True
and False
respectively.
EDIT: As pointed above, you will need to escape more characters depending on your scenario.
EDIT 2: The code below should take care of escaping any string which is part of the regular expression language. In your case, this also means the *
operator. I used the Regex.Escape
method the escape all the characters which might have a special regex meaning and then used the usual replace
to get the *
back on track.
String input2 = "file*.xml";
input2 = Regex.Escape(input2); //Yields file\\*\\.xml
input2 = input2.Replace("\\*", ".*"); //Yields file.*\\.xml
Regex regex = new Regex("^" + input2 + "$");
String input1 = "file_123.xml";
String input3 = "file_123.xml.done";
System.Console.WriteLine(regex.IsMatch(input1));
System.Console.WriteLine(regex.IsMatch(input3));
System.Console.ReadLine();