0

i want regex that only accept number format with closing and opening round brackets format like this(091)(022)(2)(123-4567)

This i want to use in C#.

Yotam Omer
  • 15,310
  • 11
  • 62
  • 65
swapnil
  • 323
  • 2
  • 6
  • 13
  • 2
    [What have you tried?](http://mattgemmell.com/2008/12/08/what-have-you-tried/) – dtsg Jun 06 '12 at 15:16
  • ^(\([0-9-]+\))+$ but its showing error on opening and closing bracket .error like this "unrecognized escape sequence". – swapnil Jun 06 '12 at 15:52

1 Answers1

3

The regular expression I would use is this:

^(\([0-9-]+\))+$

This expression will match all of it, or nothing.

To test a string against the expression in C#, it would look something like this:

var str = "(091)(022)(2)(123-4567)";
var isMatch = Regex.IsMatch(str, @"^(\([0-9-]+\))+$");
vcsjones
  • 138,677
  • 31
  • 291
  • 286
  • i tried this but its showing error like unrecognized escape sequence for the opening and closing round bracket. – swapnil Jun 06 '12 at 15:50
  • @swapnil what code are you using? (note that my string is a verbatim string) – vcsjones Jun 06 '12 at 15:52
  • void Validatetelephone(TextBox textBoxControl) { Regex rx = new Regex("^(\([0-9-]+\))+$"); if (rx.IsMatch(textBoxControl.Text)) { } else Response.Write("telephon format"); } – swapnil Jun 06 '12 at 15:55
  • @swapnil Look at my example code. You need to use a verbatim string. `new Regex(@"^(\([0-9-]+\))+$")` – vcsjones Jun 06 '12 at 15:56
  • @vjsjones ihave remove the @ from regex.i want to match this regex with the value which is enter in the texbox. – swapnil Jun 06 '12 at 16:04
  • @swapnil You *need* the @ *before* the string, not inside of it. The @ is used for a [verbatim string](http://stackoverflow.com/questions/10537578/adding-a-string-to-the-verbatim-string-literal). It is not actually part of the string. The compiler treats the string differently. – vcsjones Jun 06 '12 at 16:09