使用 Java 正則表示式驗證名字和姓氏


為了透過正則表示式匹配名字和姓氏,我們在 Java 中使用 matches 方法。java.lang.String.matches() 方法返回一個布林值,它取決於 String 與正則表示式的匹配情況。

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

public boolean matches(String regex)

我們來看一個使用正則表示式驗證名字和姓氏的程式 −

示例

 線上演示

public class Example {
   public static void main( String[] args ) {
      System.out.println(firstName("Tom"));
      System.out.println(lastName("hanks"));
   }
   // validate first name
   public static boolean firstName( String firstName ) {
      return firstName.matches( "[A-Z][a-z]*" );
   }
   // validate last name
   public static boolean lastName( String lastName ) {
      return lastName.matches( "[A-Z]+([ '-][a-zA-Z]+)*" );
   }
}

輸出

true
false

更新於: 2020 年 6 月 25 日

5K+ 次瀏覽

開啟你的 職業生涯

完成課程取得認證

開始學習
廣告
© . All rights reserved.