tags:

views:

190

answers:

2

Is there any relatively simple way to recognize Regex pattern as simple text or as a rule?

Edit

One example. @"[A-Z0-9]" - is a rule, and @"\[A-Z0-9\]" is a plain simple text (C# string syntax)

+1  A: 

Short of detecting ' [' i.e. escaped regular expression characters, I can't think of anything off the top of my head.

Since using @ copies the string literal verbatim try -

1.Finding every '['/'*'/'+'/'all other regex charachters' and ensuring that the previous charachter is a '\'.

2.Another way might be to write a grammar/regex to check this. I think you'll need a grammar. In any case (1) above is simpler.

Some string methods may help check for the above (like IndexOf ...).

In any case, a regex is just a string, unless and until it is compiled and used. I still cant see why you want to do this. If you want to ensure something is a well formed regex, that is easier. (I don't know a C# specific way for it offhand -- See Svish's answer.).

Note
1.A regex is always a rule because the regex "XYZ" is a rule that always matches "XYZ" alone and doesn't match anything else.

I hope this helps.

batbrat
This whole answer should be cleaned up and made more succinct. You don't need to provide us with a running list of "edits". We have version control on your Answer if we wish to see edits. Just focus on making your answer as to-the-point as possible.
Simucal
Maybe you are right. Unfortunately I should check escape symbols before special symbols: \, *, +, ?, |, {, [, (,), ^, $,., #. And after that I should compile Regex to check it's correctness. I will set your answer as accepted, but I wonder why the question "why you want to do this?" is asked here?
macropas
@Simucal. I'll clean up my answer. I was going to do it once I was sure I had answered the right question.
batbrat
@macropas: I meant no offence by my question. I was curious as to why you wanted to do this, since I haven't seen a need to do this in my code.
batbrat
@macropas: Thanks for accepting the answer.
batbrat
A: 

What do you mean? A regular expression is always written as a string. Doesn't matter how you write the string, it will always be a string.

If you want to check if a string is a valid regular expression on the other hand (if that is what you are asking), you can always do this:

try
{
   new Regex(someRegexString);
}
catch(ArgumentException)
{
  // Regular expression parsing error. I.e: Not a valid regular expression.
}

Now if you want to use the regular expression string, you can either use it as the string or as a regular expression. Using it as a string is just like... using it as a string... Using it as a regular expression means creating a Regex object (or using some of the static methods of Regex). If you then use it as a rule, or to replace text, or to extract stuff, or whatever, that doesn't really change anything. The regular expression is still a regular expression.

Svish