tags:

views:

25

answers:

1

I need a pattern (java regex) that will match international mobile numbers containing 7 to 17 digits with the exception that the first 3 digits can not be (965) consecutively. Thanks in advance.

+1  A: 

First (if necessary) remove all non-digits from your string, for example like this:

String sanitized_number = raw_number.replaceAll("\\D+", "");

Then check if the following is True:

boolean foundMatch = sanitized_number.matches("^(?!965)\\d{7,17}$");
Tim Pietzcker
+1 But don't you need the < for negative look-behind? As in `^(?<!965)\d{7,17}$`
Robusto
I'm looking ahead, therefore `(?!...)`. No way to look behind at the start of a string :)
Tim Pietzcker
If you're matching international numbers, would you not allow a leading '+'?
Marty
@Marty: That `+` is removed in the first step, along with all other non-numbers. I think the requirements are too vague to tell whether that's a Good Thing or not...
Tim Pietzcker
@Tim: 965 is the dialing code for Kuwait.
Gilbert Le Blanc
@Tim: Thanks a lot. Its working.@Marty: Yes, the numbers will have a leading '+' or '00'. And I'm gonna match it with '(\+|00)'.
raatprohory