Java matches() 方法
matches() 方法用於檢測字符串是否匹配給定的正則表達式
調用此方法的 str.matches(regex) 形式與以下表達式產生的結果完全相同:
Pattern.matches(regex, str)
語法
public boolean matches(String regex)
參數
regex -- 匹配字符串的正則表達式。
返回值
在字符串匹配給定的正則表達式時,返回 true。
public class Test {
public static void main(String args[]) {
String Str = new String("www.runoob.com");
System.out.print("返回值 :" );
System.out.println(Str.matches("(.*)runoob(.*)"));
System.out.print("返回值 :" );
System.out.println(Str.matches("(.*)google(.*)"));
System.out.print("返回值 :" );
System.out.println(Str.matches("www(.*)"));
}
}
以上程序執行結果為:
返回值 :true
返回值 :false
返回值 :true
Java String contains() 方法
contains() 方法用於判斷字符串中是否包含指定的字符或字符串。
public boolean contains(CharSequence chars)
參數
chars -- 要判斷的字符或字符串。
返回值
如果包含指定的字符或字符串返回 true,否則返回 false。
以下實例判斷 Runoob 中是否包含字符或字符系列:
public class Main {
public static void main(String[] args) {
String myStr = "Runoob";
System.out.println(myStr.contains("Run"));
System.out.println(myStr.contains("o"));
System.out.println(myStr.contains("s"));
}
}
以上程序執行結果為:
true
true
false