2013-11-28 62 views
0

我正在開發一個移動應用程序,用戶可以通過轉發其電話號碼向用戶註冊該應用程序。電話號碼必須以「07」開頭。下面是我的代碼如何編寫電話號碼正則表達式

public boolean isPhoneNumber(String s) { 
    String pattern = "[0-9]"; 
    if (s.matches(pattern)) { 
     return true; 
    } 
    return false; 
} 

任何想法左右我從這裏

+0

檢查這個環節上的各種正則表達式:http://regexlib.com/(A(3k11t-l-bx51TbStx_502eQq_kMPKrbAUku29jOowfM7aos6m8LTywGmKyLQ9PvcrjtaYPs4AczP5NXz2h7ZVMCGJSGrq8WHjaHgNAZ4GUc1))/DisplayPatterns.aspx?cattabindex=6&categoryId=7 –

+0

國家前綴呢?一些用戶將包括它,其他用戶不會。 – NickT

回答

1

如何進行您當前的表達將允許,只要它包含09之間的數字任意字符串傳遞。

相反,你需要下面的表達式:

^07 
  • ^:比賽開始-的字符串。
  • 0:匹配文字0
  • 7:匹配文字7

在Java:

public boolean isPhoneNumber(String s) { 
    String pattern = "^07"; 
    if (s.matches(pattern)) { 
     return true; 
    } 
    return false; 
} 
+0

我該如何寫這個表達式?我已經嘗試^ 07 [0-9],但它不工作 –

+0

@williamjingo我編輯了我的答案,請檢查編輯。 –

+0

@williamjingo你還有什麼問題嗎? –

0

你可以試試這個:^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$

1

使用\ d檢查字符是數字或沒有。例如。 \ d {6}將檢查是否有6個隨後的數字。 在這裏,你正在尋找代碼:

public static boolean isPhoneNumber(String s) { 
    String pattern = "^07\\d{6}"; 
    if (s.matches(pattern)) { 
     return true; 
    } 
    return false; 
} 

檢查了這一點,瞭解更多關於正則表達式:http://www.vogella.com/articles/JavaRegularExpressions/article.html

0

例如,它是一個10位數的手機號碼,你可以試試下面

 public static boolean isPhoneNumber(String s) { 
     String pattern = "^[0-9]{10}"; 
     if (s.matches(pattern)) { 
     return true; 
     } 
     return false; 
     }