Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect exact length in regex

Tags:

regex

I have two regular expressions that validate the values entered.

One that allows any length of Alpha-Numeric value:

@"^\s*(?<ALPHA>[A-Z0-9]+)\s*"

And the other only allows numerical values:

@"^\s*(?<NUM>[0-9]{10})"

How can I get a numerical string of the length of 11 not to be catched by the NUM regex.

like image 597
CheGueVerra Avatar asked Apr 24 '09 20:04

CheGueVerra


People also ask

How do I limit the length of a string in regex?

By combining the interval quantifier with the surrounding start- and end-of-string anchors, the regex will fail to match if the subject text's length falls outside the desired range.

What does * do in regex?

The Match-zero-or-more Operator ( * ) This operator repeats the smallest possible preceding regular expression as many times as necessary (including zero) to match the pattern. `*' represents this operator. For example, `o*' matches any string made up of zero or more `o' s.

How do you match a space in regex?

If you're looking for one or more, it's " *" (that's two spaces and an asterisk) or " +" (one space and a plus). If you're looking for common spacing, use "[ X]" or "[ X][ X]*" or "[ X]+" where X is the physical tab character (and each is preceded by a single space in all those examples).


1 Answers

I think what you're trying to say is that you don't want to allow any more than 10 digits. So, just add a $ at the end to specify the end of the regex.

Example: @"^\s*(?[0-9]{10})$"


Here's my original answer, but I think I read you too exact.

string myRegexString = `@"(?!(^\d{11}$)` ... your regex here ... )";

That reads "while ahead is not, start, 11 digits, end"

like image 188
Timothy Khouri Avatar answered Sep 22 '22 16:09

Timothy Khouri