使用 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 次查看

开启你的事业

完成课程获得认证

开始
广告
© . All rights reserved.