开发者

Regex to restrict only one occurrence of open and close brackets using C#

How to make sure I don't allow more than one brackets "(" and ")" in the input text? I have the following expression that will allow numbers, spaces, hyphens and brackets.

Regex.Match(text, @"^[0-9 (,),-]+$").Success

I don't what to allow something like "((123) 456-7891 or (91)123-23123(1). The correct string can be: "(123) 1231231 or (121)123-213123.

Edited: Sorry for not being clear. Requirement is to only allow numbers, spaces, hyphens and brackets (one se开发者_JAVA技巧t only). To be specific, "(" should always have a closing bracket ")". As one of you said no paren or one set of paren. If someone can also tell how to allow the paren at any position not only at the start?


This will do it:

@"^(?:[^()]*|[^()]*\([^()]*\)[^()]*)$"

and only allowing numbers, hyphens and spaces:

@"^(?:[-0-9 ]*|[-0-9 ]*\([-0-9 ]*\)[-0-9 ]*)$"

This basically says that either there are no parens, or there can be only one set of parens. If you only want strings that have exactly one set of parens, you can use this simpler form:

@"^[^()]*\([^()]*\)[^()]*$"

and only allowing numbers, hyphens and spaces:

@"^[-0-9 ]*\([-0-9 ]*\)[-0-9 ]*$"


^[^\(\)]*\([^\(\)]*\)[^\(\)]*$

worked for me based on your examples. This will not, however, ensure that the rest of the phrase is numbers. for instance, this regex will match both (123) 1231231 and abc(def)ghi Let me know if this is ok.


If it's always open-bracket followed by 3 numbers, then close-bracket, put that into the regex:

@"^\(\d{3}\)\s?\d{3}-?\d{4}$"

That is, open-bracket, three numbers, close bracket, optional space, three numbers, optional hyphen, four numbers.


What you are asking and what you want are probably two different things :-) Some examples:

  • 1231234(12)
  • 1231234
  • )1231234
  • (123412

Are they legal?

Start with this:

Legal:

  • 123456
  • 1234-456
  • (123)345
  • (123) 345
  • (123)345-678
  • (123) 345 678

Regex:

@"^(\(\[0-9]+\) ?)?\[0-9]+(-\[0-9]+)?$"


I think this will work for the above instances you specified:

Regex.Match(text, @"^\([0-9]{3}\)\s?[0-9]{3}-?[0-9]+$").Success

This will match any number of digits at the end of the string. You did not specify how many are allowed. If you wanted to make this more specific you could replace the last + sign with {4,6} where 4 is the minimum number of digits after the - and 6 is the maximum.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜