laitha0
laitha0

Reputation: 4336

Regex patterns to distinguish four digit numbers

Hi I have a c# application where it accepts a 4 digit extension number and sets up a mask for it. I have a situation where two different masks need to be applied depending on the number.

First: If the number starts with 47 or 5 return mask A.

Second: If the number starts with 6 or 55 return mask B. 

So I setup my Regex this way and I am not sure why its getting set wrong.

//Here I am trying to say, anything that start with 47 or 5 with the next 3 digits taking any number
Match first = Regex.Match(num, "^(47|(5[0123456789]{3}))");

//anything that start with 6 or 55 with the next 2 digits taking numbers 0-5
Match secong = Regex.Match(num, "(6|55[123450]{2})");

If I give use the above with input num=5850 or num=5511 it will be true for both but clearly 5850 should use Mask A and 5511 should use Mask B

How do I fix this??

Thanks!

Upvotes: 0

Views: 462

Answers (4)

gpmurthy
gpmurthy

Reputation: 2427

Consider the following...

Match first = Regex.Match(num, "^(47[0-9]{2}|5[0-9-[5]]{1}[0-9]{2})");

Match second = Regex.Match(num, "^(6[0-9]{3}|55[0-9]{2})");

Upvotes: 2

Drake Clarris
Drake Clarris

Reputation: 1045

I think this will cover you. note you can use \d for 0-9, a range for 0-5, and you left the boundary indicator (^) off the second one. Note I didn't use a range or \d for the first part of the first one, because you don't want to match 55. Notice also the grouping.

//anything that start with 47 or 5 with the next 3 digits taking any number (but not 55!)
Match first = Regex.Match(num, "^((47|5[012346789])\d{2})");

//anything that start with 6 or 55 with the next 2 digits taking numbers 0-5
Match secong = Regex.Match(num, "^((6|55)[0-5]{2})");

Upvotes: 1

Syon
Syon

Reputation: 7401

These should do it for you.

This matches any 4 digit number starting with 47 or 5, excluding 5 as the second digit.

^(47|5([0-4]|[6-9]))\d{2}$

This matches any 4 digit number starting with 6 or 55.

^(6\d|55)\d{2}$

Upvotes: 1

It looks like you should use 4 regular expressions

/^47\d{3}/

/^5\d{4}/

/^6\d{4}/

/^55\d{3}/

notice how numbers that begin with 55 are a match for both of your cases, but the reverse doesn't work for numbers that begin with 5 you should use that fact to distinguish between them


if you want to combine regular expressions, than that's fine

/(^47\d{3})|(^5\d{4})/

note: you might also want to use the end of input anchor: $ or a word boundary or negative look-ahead to match the end of output too.

Upvotes: 0

Related Questions