使用 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP