使用 Java 正則表示式驗證電話


為了使用正則表示式匹配電話,我們在 Java 中使用 matches 方法。java.lang.String.matches() 方法返回布林值,該值取決於字串與正則表示式的匹配情況。

宣告 − java.lang.String.matches() 方法的宣告如下 −

public boolean matches(String regex)

讓我們編寫一個使用正則表示式驗證電話號碼的程式 −

示例

 現場演示

public class Example {
   public static void main( String[] args ) {
      System.out.println(phone("+91 1023456789"));
   }
   // validate zip
   public static boolean phone( String z ) {
      return z.matches("\+[0-9]*\s+\d{10}" );
      // taking an assumption that a phone number is of ten digits
   }
}

輸出

true

更新日期:25-6 月-2020

314 次檢視

開啟你的事業

完成課程獲得認證

開始
廣告