使用 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