A regex restricts only one occurrence of open and closed brackets using C #

How to make sure that I do not allow more than one parenthesis "(" and ")" in the input text? I have the following expression that will allow numbers, spaces, hyphens and brackets to be used.

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

I can’t allow something like "((123) 456-7891 or (91) 123-23123 (1)). The correct line could be:" (123) 1231231 or (121) 123-213123.

Edited: Sorry for not understanding. The requirement is to allow only numbers, spaces, hyphens and brackets (only one set). To be specific, "(" must always have a closing bracket ")". As one of you said, not one guy or one set of guys. If someone can also say how to allow a guy in any position, not only in the beginning?

+4
source share
5 answers

This will be done:

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

and allows only numbers, hyphens, and spaces:

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

Basically, this suggests that either there are no partners, or there can only be one set of guys. If you only need strings containing exactly one set of parsers, you can use this simpler form:

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

and allows only numbers, hyphens, and spaces:

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

worked for me based on your examples. However, this does not guarantee that the rest of the phrase is numbers. for example, this regular expression will match both (123) 1231231 and abc(def)ghi . Let me know if this is normal.

+1
source

What you ask and what you want, maybe these are two different things :-) Some examples:

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

Are they legal?

Start with this:

Allowed:

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

Regex:

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

If this is always an open bracket followed by 3 numbers, then copy it, put it in the regular expression:

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

That is, an open bracket, three numbers, a closing bracket, extra space, three numbers, an optional hyphen, four numbers.

+1
source

I think this will work for the above instances:

 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 line. You did not indicate how many are allowed. If you want to make it more specific, you can replace the last + sign with {4.6}, where 4 is the minimum number of digits after - and 6 is the maximum.

0
source

Source: https://habr.com/ru/post/1339737/


All Articles