您好,我在為以下條件創建正則運算式(電話號碼)時遇到問題:
- 必須恰好包含 13 個字符
- 只能從 421 或 420 開始
- 只有數字必須跟隨
- 必須忽略空格
最后的格式必須是:
421 xxx xxx xxx或 420 xxx xxx xxx
到目前為止,我已經創建了類似的東西,但我不知道如何進行。
const regexPhone = /^\ [0-9]{12}/i;
你能幫我嗎?
uj5u.com熱心網友回復:
正則運算式模式通常是根據文本“外觀”創建的,例如在您的示例中,數字應該看起來像“ 420 xxx xxx xxx”,那么為什么不為這種確切的格式制作正則運算式呢?
嘗試這個:/^\ 42[10] \d{3} \d{3} \d{3}$/
let pattern = /^\ 42[10] \d{3} \d{3} \d{3}$/
let s = " 421 543 100 478"
console.log(pattern.test(s))
現在您可以將上述正則運算式簡化為/^\ 42[10]( \d{3}){3}$/
^ matches the start of the string
\ matches
42[10] matches 42 followed by either 1 or 0
( \d{3}){3} matches a space followed by three digits, this inturn is matched exactly three times
$ matches the end of the string
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/457124.html
標籤:正则表达式
