-1

I would like to validate a telephone number which can contain 10 to 13 digit numbers and can contain 0 to 3 spaces (can come anywhere in the data). Please let me know how to do it?

I tried using regex ^(\d*\s){0,3}\d*$ which works fine but I need to restrict the total number of characters to 13.

Kara
  • 6,115
  • 16
  • 50
  • 57
sdinreach
  • 9
  • 3
  • 1
    Welcome to SO. Please read [about what kind of questions you can ask here](http://stackoverflow.com/help/on-topic). Specifically: "Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results." – us2012 Sep 28 '13 at 22:15
  • I tried regex ^(\d*\s){0,3}\d*$ which works fine but I need to restrict the number of characters to 13. So I tried ^((\d*\s){0,3}\d*){10,13}$ but didn't work. I am new to regex. – sdinreach Sep 28 '13 at 22:43
  • possible duplicate of [A comprehensive regex for phone number validation](http://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation) – John Dvorak Sep 29 '13 at 05:50
  • @@Jan - that topic discusses other match-conditions, this question is much more focused on ability to combine regexps - http://stackoverflow.com/questions/869809/combine-regexp – Vlad Sep 29 '13 at 06:01

1 Answers1

0

You want to match same text against 2 different whole-line patterns.

It's achievable either by matching patterns consequently:

$ cat file
1234567 90
1234567890
123 456 789 0123
123 456 789 01 23
$ sed -rn '/^([0-9] ?){9,12}[0-9]$/{/^([0-9]+ ){0,3}[0-9]+$/p}' file
1234567890
123 456 789 0123
$

Or if Your regex engine (perl/"grep -P"/java/etc) supports lookaheads - patterns can be combined:

// This is Java
Pattern p = Pattern.compile("(?=^([0-9] ?){9,12}[0-9]$)(?=^([0-9]+ ){0,3}[0-9]+$)^.*$");
System.out.println(p.matcher("1234567 90").matches());        // false
System.out.println(p.matcher("123 456 789 0123").matches());  // true
System.out.println(p.matcher("123 456 789 01 23").matches()); // false
Community
  • 1
  • 1
Vlad
  • 1,157
  • 8
  • 15
  • Vlad! Thanks for your answer. When I tried 1234 890, its matching but I want to match the input to have at least 10 digits. – sdinreach Sep 29 '13 at 08:23
  • @@sdinreach, "1234 890" is NOT matching - see http://ideone.com/AEaJdF or paste sample of how You apply it – Vlad Sep 30 '13 at 02:02
  • Sorry Vlad! it was "123456 789". I would like to regex to match atleast 10 numbers before allowing 3 spaces. Please let me know how to do it? – sdinreach Sep 30 '13 at 11:25
  • @@sdinreach - I've updated the answer to match Your requirements :) http://ideone.com/sDTfWP – Vlad Oct 01 '13 at 02:03