Possible Duplicate:
How do I check if a filename matches a wildcard pattern
In the program that I am doing, the user has two inputs.
Input 1 = the filename.
Input 2 = the flagFilePatternex. 1
Input 1 = file1.xml or file25.xml or file_123.xml
Input 2 = file*.xml
Result (all files should match based on the
pattern(Input 2)ex. 2
Input 1 = file1.xml.done
Input 2 = file*.xml
Result (the file should not match based on the pattern, because .xml
was not found at the last of the filename).
Question, what should be my regular expression based on the example above?
Note: my code is in C#
The value for
input 2can 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:The
.is a special character in regex so it needs to be escaped. The secondreplacestatement adds a.which means any character infront of the*operator which means or or more repetitions of. The code above yieldsTrueandFalserespectively.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 theRegex.Escapemethod the escape all the characters which might have a special regex meaning and then used the usualreplaceto get the*back on track.