1/*
2
3 * Copyright (C) 2011 The Android Open Source Project
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 *      http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18package com.android.ex.chips;
19
20import android.text.TextUtils;
21
22import java.util.regex.Matcher;
23import java.util.regex.Pattern;
24
25/**
26 * A utility class for chips using phone numbers.
27 */
28public class PhoneUtil {
29
30    // This pattern comes from android.util.Patterns. It has been tweaked to handle a "1" before
31    // parens, so numbers such as "1 (425) 222-2342" match.
32    private static final Pattern PHONE_PATTERN
33            = Pattern.compile(                                  // sdd = space, dot, or dash
34                    "(\\+[0-9]+[\\- \\.]*)?"                    // +<digits><sdd>*
35                    + "(1?[ ]*\\([0-9]+\\)[\\- \\.]*)?"         // 1(<digits>)<sdd>*
36                    + "([0-9][0-9\\- \\.][0-9\\- \\.]+[0-9])"); // <digit><digit|sdd>+<digit>
37
38    /**
39     * Returns true if the string is a phone number.
40     */
41    public static boolean isPhoneNumber(String number) {
42        // TODO: replace this function with libphonenumber's isPossibleNumber (see
43        // PhoneNumberUtil). One complication is that it requires the sender's region which
44        // comes from the CurrentCountryIso. For now, let's just do this simple match.
45        if (TextUtils.isEmpty(number)) {
46            return false;
47        }
48
49        Matcher match = PHONE_PATTERN.matcher(number);
50        return match.matches();
51    }
52}
53