I have an input which gets a statement from the user. According with the usage of my program, users can enter a character or a regular expression. After filling this input, users have to fill a second input that is the replacement text.
The problem is, user can type . and this is equivalent to a regular expression, which matches any character.
Does the below code work? Or, what’s the solution?
Match m = Regex.Match(input, pattern);
if( m.Success )
// it's regex
else
// it's not regex
You can’t*.
Let’s look at how Visual Studio solves this problem:
As you can’t tell whether or not the user intended the content to be a regular expression, the designers allow the user to choose, giving the user complete control over how they want the search to be performed. If you want it to be plain text (the default), just hit Find Next. Otherwise, you can tailor your search using the additional options.
*Well, you kind of can
The other approach to this problem is to assume the user meant to search using every technique you support, and filter the results; grouped by “Plain Text” matches, and “Regular Expression” matches. This is less efficient but could be considered more user friendly as the user doesn’t actively have to choose any options. So you first search by just plain text, and return those matches under the heading “Plain Text Matches”, and then search assuming the string is a regular expression, and return those matches under the heading “Regular Expression Matches”
Once you have displayed these to the user, they can choose which one they actually meant for the replace.