Validate US Telephone Numbers
Return true if the passed string is a valid US phone number.
The user may fill out the form field any way they choose as long as it is a valid US number. The following are examples of valid formats for US numbers (refer to the tests below for other variants):555-555-5555 (555)555-5555 (555) 555-5555 555 555 5555 5555555555 1 555 555 5555For this challenge you will be presented with a string such as
800-692-7753or8oo-six427676;laskdjf. Your job is to validate or reject the US phone number based on any combination of the formats provided above. The area code is required. If the country code is provided, you must confirm that the country code is 1. Return true if the string is a valid US phone number; otherwise return false.
Here are some helpful links:
檢查傳入的字符串是否為美國電話號碼,并返回真假。
由所給示例可以看出。美國電話一共分為3個(gè)部分:
- 第一部分是可以沒有的國家代碼,固定為1
- 第二部分是區(qū)號,長度固定為3
- 第三部分是電話號碼,長度為7
對于電話號碼,用正則匹配是最簡單的。
這里先匹配電話號碼。

\d{7}能識別連續(xù)7位數(shù)的電話號碼,但示例中有分隔為3+4形式的號碼,因而改寫為符合3+4形式的正則,這里暫且假定分隔符為1個(gè)空格。

\d{3} \d{4}能識別被空格分隔的7位電話號碼了,但還不夠,現(xiàn)在在加上沒有空格和有短橫線的情況。

到這就已經(jīng)完成電話號碼了,接下來做區(qū)號。
區(qū)號有且只有3位數(shù),但可能被()包裹著,與電話號碼間可能隔著空格、短橫線抑或什么都沒有。這里先處理可能被()包裹的情況。

\(\d{3}\)匹配到了()以及里面的內(nèi)容,但有的區(qū)號并沒有被括號包裹。在加上這種情況。

現(xiàn)在將區(qū)號和電話號碼連在一起。

行百里者半于九十,這里已經(jīng)完成一半了,最后來考慮國家代碼的問題。
美國的國家代碼為1,先考慮是否以1開頭。

考慮開頭的1不存在的情況。

由示例得出國家代碼與區(qū)號之間可能有1個(gè)空格。
先是有空格的。

然后是沒有空格的。

現(xiàn)在匹配美國電話號碼的正則表達(dá)式已經(jīng)基本完成了。再考慮下添加了非法字符的情況。上面的正則能匹配到前一部分是美國電話的號碼,但不能避免末尾添加了其他字符的情況。

因此還需要加上末尾的判斷。

大功告成?,F(xiàn)在編寫函數(shù)來測試一下數(shù)據(jù)。
function telephoneCheck(str) {
return /^1? ?(\(\d{3}\)|\d{3})[ |-]?\d{3}[ |-]?\d{4}$/.test(str);
}
測試結(jié)果如下圖。

測試結(jié)果顯示編寫的函數(shù)如期運(yùn)行,這樣FCC的高級算法第一題就完成了。
PS. 圖中所用正則測試工具為開源中國的在線正則表達(dá)式測試