CheGueVerra
CheGueVerra

Reputation: 7963

How to detect exact length in 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.

Upvotes: 16

Views: 63955

Answers (8)

DAVIS BENNY 15MIS0426
DAVIS BENNY 15MIS0426

Reputation: 228

var pattern =/\b[0-9]{10}$\b/;

// the b modifier is used for boundary and $ is used for exact length

Upvotes: 1

Shea
Shea

Reputation: 11243

You could try alternation?

^\s*(?\d{1,10}|\d{12,})

Upvotes: 0

Timothy Khouri
Timothy Khouri

Reputation: 31845

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"

Upvotes: 28

Imran
Imran

Reputation: 91009

This should match only 10 digits and allow arbitrary numbers of whitespaces before and after the digits.

Non-capturing version: (only matches, the matched digits are not stored)

^\s*(?:\d{10})\s*$

Capturing version: (the matched digits are available in subgroup 1, as $1 or \1)

^\s*(\d{10})\s*$

Upvotes: 0

Alan Moore
Alan Moore

Reputation: 75232

Do you mean you want to match up to 10 digits? Try this:

@"^\s*[0-9]{1,10}\s*$"

Upvotes: 2

Bryan
Bryan

Reputation: 2870

If you are trying to match only numbers that are 10 digits long, just add a trailing anchor using $, like this:

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

That will match any number that is exactly 10 digits long (with optional space on either side).

Upvotes: 1

JP Alioto
JP Alioto

Reputation: 45117

If it's single line, you could specify that your match must happen at the end of the line, like this in .net ...

^\s*([0-9]{10})\z

That will accept 1234567890 but reject 12345678901.

Upvotes: 5

Michael Kohne
Michael Kohne

Reputation: 12044

Match something non-numeric after the length 10 string. My regex-foo isn't that good, but I think you've got it setup there to catch a numeric string of exactly length 10, but since you don't match anything after that, a length 11 string would also match. Try matching beyond the end of the number and you'll be good.

Upvotes: 0

Related Questions