-1

How to find whether a string is a regular expression or normal string in C#. I find in java and PHP but not C#. Can anyone help me please. String testing = "Final";

I want to test whether "testing" is a regular expression or normal string.

Thankyou

Madhu
  • 29
  • 4
  • 5
    What do you mean? Most normal strings can also be used as regular expressions. – Cristian Lupascu Sep 27 '16 at 07:20
  • string testing = "(\d{1,2})(,)(\s*)(\d{1,4})"; – Madhu Sep 27 '16 at 07:22
  • Indeed... I'm confused as to what you'd do in the other languages, too. Not all strings are valid regular expressions of course, but all regular expressions are also normal strings. – Jon Skeet Sep 27 '16 at 07:22
  • @Madhu: Right, that's a normal string as well as a valid regular expression. – Jon Skeet Sep 27 '16 at 07:22
  • string testing1 = "Final". Here testing contains regular expression. where as testing1 contains just a normal string. – Madhu Sep 27 '16 at 07:22
  • 1
    check here http://stackoverflow.com/questions/172303/is-there-a-regular-expression-to-detect-a-valid-regular-expression – dumb_terminal Sep 27 '16 at 07:23
  • So you need an expression to match expressions? – MakePeaceGreatAgain Sep 27 '16 at 07:23
  • I mean i just want to find whether has any expressions or not – Madhu Sep 27 '16 at 07:24
  • Why not see if you can parse it into c# `RegEx` object? –  Sep 27 '16 at 07:25
  • yes i just want to filter all the strings that has expressions in it – Madhu Sep 27 '16 at 07:25
  • 1
    `"Final"` is a correct regular expression. `"^[^a]*$"` is a valid "normal string" if someone wanted to get fancy. You can get close but you'd have to decide what _counts_ as a regular expression yourself. What methods do you use in Java/PHP? Perhaps their docs explain what validation rules they use. – C.Evenhuis Sep 27 '16 at 07:31
  • yes tried with new Regex(testing); With always gives true because testing and testing1 both are valid regular expressions as said by Jon – Madhu Sep 27 '16 at 07:36
  • Yes. you are right. Thank you – Madhu Sep 27 '16 at 07:38

2 Answers2

1

you can try by exception handling

private static bool IsValidRegex(string input)
{ 
   try
   {
     Regex.Match("", input);
   }
   catch (ArgumentException)
   {
      return false;
   }

  return true;
}
Visakh V A
  • 320
  • 3
  • 19
1

You can evaulate string in Regex

private static bool IsValidRegex(string pattern)
{
    if (string.IsNullOrEmpty(pattern)) return false;

    try {
        Regex.Match("", pattern);
    }
    catch (ArgumentException){
        return false;
    }

    return true;
}

If method returns false you can accept this string as normal string.

Dakmaz
  • 61
  • 6