Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression for Norwegian numbers

Tags:

java

regex

I am trying to write regular expression that is going to match all phone numbers in Norway. That means that number can begin with +47, 0047, 47 or without country code. To achieve that I am using following regular expreession:

Pattern.compile("^((0047)?|(\"+47)?|(47)?)\"d{8}$")

The problem is that it is never matched. I am testing it on the following valid examples:

90909090,   normal number
4790909090, number with country code
+4790909090, country code using +
004790909090, country code using 00

and invalid:

+47909090, without country code or too short number
9090909o,  invalid character
9090909,  too few digits
+4690909090, wrong country code
909090909, too many digits
00474790909090 Trying to fool the regex now
like image 946
Sanja Avatar asked Feb 21 '26 10:02

Sanja


2 Answers

Think you're looking for

(0047|\+47|47)?\d{8} 

which in your Java expression would be:

Pattern.compile("(0047|\\+47|47)?\\d{8}"); 
like image 87
Sami Farhat Avatar answered Feb 23 '26 00:02

Sami Farhat


Sami's answer is nearly correct, but would not be able to identify numbers starting with 0 or 1. Numbers starting with 0 is not allowed and numbers starting with 1 are reserved in Norway (ref). The following should work:

/^(0047|\+47|47)?[2-9]\d{7}$/

In your Java expression:

Pattern.compile("^(0047|\+47|47)?[2-9]\d{7}$")
like image 25
oyvindym Avatar answered Feb 23 '26 01:02

oyvindym



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!