Sam_Web
Sam_Web

Reputation: 125

More RegEx problems - UK phone numbers - Bash

I'm having yet more problems with my RegEx, This time, i have to ask a user to enter their phone number then check it is correct.

i have tried the following:

if [[ "$number" =~ ^[\(]?[\+44,0][1-9][0-9]{3}[\)]?[\ ]?[0-9]{6} ]]
then
    echo "YEP"
else
    echo "NOPE"
fi

I've also had a mess around with slightly varying the RegEx...

this seems to work with numbers like:

07384323455
(01273)277364
01677 336482

But not with any numbers with the +44 in it...

Is there anything i am doing terribly wrong or anything anyone can suggest?

Thanks in advance,

Sam

Upvotes: 0

Views: 389

Answers (2)

koola
koola

Reputation: 1734

Try the following

#!/bin/bash
for number in '07384323455' '(01273)277364' '01677 336482' '+447384323455' '(+447384)323455' '+7384323455' '(+437384)323455'
do
    if [[ "$number" =~ ^[\(]?(\\+44|0){1}[1-9]{1}[0-9]{3}[\)]?[\ ]?[0-9]{6} ]];
    then
        echo "YEP"
    else
        echo "NOPE"
    fi
done

Output

YEP
YEP
YEP
YEP
YEP
NOPE
NOPE

Explanation

  • (\\+44|0){1} - Matches the character sequence +44 or | zero 0, capture group matches exactly once.

Upvotes: 0

Firas Dib
Firas Dib

Reputation: 2621

Try out this expression: ^(?:\((?:\+44\d{4}|\d{5})\)|\+44\d{3}|\d{5}) ?\d{6}$

Demo+explanation: http://regex101.com/r/lC5kM6

Here's an explanation for your expression: regex101.com/r/gT5oT8 (try to figure out your errors)

Upvotes: 1

Related Questions