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

开启你的 职业

完成课程获得认证

开始
广告
© . All rights reserved.