How can I check if a string is a string or RegEx?

How can I check if a string in a textbox is a plain string using RegEx?

I am looping through a text file line by line.

Either .Contains(Textbox.Text);

orRegex(Textbox.Text) Match(currentLine)

(i know the syntax doesn't work like this, it's just for presentation)

Now my program should autodetect if it Textbox.Text

is in RegEx form or if it is a normal string.

Any suggestions? Write my own little RexEx to determine if the Textbox contains RegEx?

Edit:

I was unable to add thad my Strings can be very simple like Foo ore 0005 I'm trying the suggested solutions right now!

+2


source to share


4 answers


You cannot find regular expressions with regex as the regex itself is not a regular language.

However, the easiest way you could probably do is to try and compile a regex from your textbox content, and when it succeeds, you know it is a regex. If it fails, you don't know.



But this classifies regular strings like "foo" as a regular expression. Depending on what you need to do, this may or may not be a problem. If it is a search string, then the results for this case are identical. In the case of "foo.bar" they will be different, although since this is a valid regex, it matches different things than the string itself.

My advice, also laid out in another comment, would be that you just always include the regex search, as it makes no difference if you strip the code points here. Aside from questionable performance (which hardly matters if there is a lot of benefit).

+5


source


Many strings can be a regex, each regex can be a string.

Consider the string "thin". can be either a string ("." is a period) or a regular expression ("." is any character).



I would just add a checkbox where the user specifies if it is part of a regex, as is usual in many applications.

+3


source


One possible solution, depending on your definition of string and regex, would be to check if the string contains any typical regex characters.

You can do something like this:

string s = "I'm not a Regex";

if (s == Regex.Escape(s))
{
   // no regex indeed
}

      

+2


source


Try using it in a regular expression and see if an exception is thrown.

This approach only checks if it is a valid regex, not if it was intended for it.

Another approach might be to check if it is surrounded by a forward slash (eg "/ foo /"). Regular slash regex rules (although you should remove slashes before loading them into the regex library)

0


source







All Articles