使用 Java 正則表示式驗證城市和州


為了使用正則表示式匹配城市和州,我們使用 Java 中的 matches 方法。java.lang.String.matches() 方法返回一個布林值,該值取決於字串與正則表示式的匹配程度。

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

示例

 線上演示

public class Example {
   public static void main( String[] args ) {
      System.out.println(city("Mumbai"));
      System.out.println(state("Goa"));
   }
   // validating the city
   public static boolean city( String c ) {
      return c.matches( "([a - zA - Z] + |[a - zA - Z] + \s[a - zA - Z] + )" );
   }
   // validating the state
   public static boolean state( String st ) {
      return st.matches( "([a - zA - Z] + |[a - zA - Z] + \s[a - zA - Z] + )" ) ;
   }
}

輸出

false
false

更新時間: 25-6 月 -2020

927 次檢視

開啟你的 職業

完成課程獲得認證

開始
廣告