21
Your task is to write a program or function that checks if a string is a valid phone number.
Given a string (or list of characters/codepoints) input, you will output a truthy value if the input is a valid phone number. If it is not, output a falsey value. An input string is considered a valid phone number for this challenge if it meets all of these criteria:
- It contains ten digits, which are grouped like this:
###-###-####
- The strings separating the digit groups must be the same
- The first and last characters must be part of the phone number (i.e. must not be part of a separator)
Test cases:
111-222-3333 truthy
123-456-7890 truthy (number groups can contain different numbers)
1112223333 truthy (can have 0 length separators)
111022203333 falsey (has more than 10 numbers)
111ABC222ABC3333 truthy (can have length>1 separators)
111-222_3333 falsey (non-matching separators)
111-22-23333 falsey (missing digit in middle group)
111--222--33333 falsey (extra digit in last group)
-111-222-3333 falsey (first character is not part of number)
111-222-3333a falsey (last character is not part of number)
aaa-aaa-aaaa falsey (not enough numbers)
11-2222-3333 falsey (wrong separator location)
111-1-222-1-3333 falsey (too many numbers)
This is a code golf challenge, shortest answer per language wins.
Can we return two consistent values instead of truthy/falsey? – Adám – 2019-11-04T21:54:57.480
@Adám Such as? I'd be fine with
t
/f
ortrue
/false
– Redwolf Programs – 2019-11-07T13:27:35.467How about
" "
for true and""
for false? – Adám – 2019-11-07T13:30:22.477@Adám I'd be fine with that, if it's the fairest solution in whatever language you are using – Redwolf Programs – 2019-11-07T13:31:26.833
I don't know how to judge fairest, but it is quite common here to allow any two values for [tag:decision-problem] challenges. It definitely isn't the normal true and false. – Adám – 2019-11-07T13:32:23.477
@Adám Makes sense. I'd accept
" "
and""
, especially since I consider an empty string to be falsey anyway – Redwolf Programs – 2019-11-07T13:34:38.537