str.matches() 方法 str.contains() 方法


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM