How to Check if a String is a "string" or a RegEx?

.net, c#, regex

Solution

You can't detect regular expressions with a regular expression, as regular expressions themselves are not a regular language.

However, the easiest you probably could do is trying to compile a regex from your textbox contents and when it succeeds you know that it's a regex. If it fails, you know it's not.

But this would classify ordinary strings like "foo" as a regular expression too. Depending on what you need to do, this may or may not be a problem. If it's a search string, then the results are identical for this case. In the case of "foo.bar" they would differ, though since it's a valid regex but matches different things than the string itself.

My advice, also stated in another comment, would be that you simply always enable regex search since there is exactly no difference if you split code paths here. Aside from a dubious performance benefit (which is unlikely to make any difference if there is much of a benefit at all).

Problem

How can I check if a String in an textbox is a plain String ore a RegEx? I'm searching through a text file line by line. Either by `.Contains(Textbox.Text);` or by `Regex(Textbox.Text) Match(currentLine)` (I know, syntax isn't working like this, it's just for presentation) Now my Program is supposed to autodetect if `Textbox.Text` is in form of a RegEx or if it is a normal String. Any suggestions? Write my own little RexEx to detect if Textbox contains a RegEx? Edit: I failed to add thad my Strings can be very simple like Foo ore 0005 I'm trying the suggested solutions right away!

Original source