Regular expression to match phone number?

I want to match a phone number that can have letters and an optional hyphen:

  • It Really: 333-WELL
  • This is also true: 4URGENT

In other words, there can be no more than one hyphen, but if there is no hyphen, there can be no more than seven characters 0-9 or AZ.

I do not know how to do this and the "if statement" in the regex. Is it possible?

+2
source share
5 answers

You are looking for a rotation operator, indicated by a pipe symbol: |

However, you may need either 7 alternatives (1 for each hyphen + 1 for the hyphen), or you may need a hyphen between the 3rd and 4th characters and use 2 options.

One use of the rotation operator defines two alternatives, for example:

 ({3,3}[0-9A-Za-z]-{4,4}[0-9A-Za-z]|{7,7}[0-9A-Za-z]) 
+4
source

I think this should do it:

 /^[a-zA-Z0-9]{3}-?[a-zA-Z0-9]{4}$/ 

It matches 3 letters or numbers, followed by an additional hyphen, and then 4 letters or numbers. It works in ruby. Depending on the regular expression engine you use, you may need to modify it a bit.

+5
source

Not sure if this counts, but I split it into two regular expressions:

 #!/usr/bin/perl use strict; use warnings; my $text = '333-URGE'; print "Format OK\n" if $text =~ m/^[\dA-Z]{1,6}-?[\dA-Z]{1,6}$/; print "Length OK\n" if $text =~ m/^(?:[\dA-Z]{7}|[\dA-Z-]{8})$/; 

This should avoid taking multiple dashes, dashes in the wrong place, etc.

+1
source

Suppose that you want the hyphen to be anywhere, the images will be useful to you. Something like that:

 ^([A-Z0-9]{7}|(?=^[^-]+-[^-]+$)[A-Z0-9-]{8})$ 

This template has two main parts: [A-Z0-9]{7} for matching a line without a hyphen and (?=^[^-]+-[^-]+$)[A-Z0-9-]{8} to match the wrapped string.

(?=^[^-]+-[^-]+$) will match any line with a SINGLE hyphen (and the hyphen is not the first or last character), then the [A-Z0-9-]{8} will count characters and make sure they are all valid.

+1
source

Thanks to Heath Hunnicutt for his answer to the rotation operator, and also show me an example.

Based on his advice, here is my answer:

 [A-Z0-9]{7}|[A-Z0-9][A-Z0-9-]{7} 

Note. I checked my regex here . (Just turning it on for reference)

0
source

All Articles