使用 find() 在 Java 正則表示式中查詢子序列
find() 方法在輸入序列中查詢與所需模式匹配的子序列。此方法在 java.util.regex 包中 Matcher 類中提供。
下面的程式使用了 find() 方法在 Java 中查詢子序列
示例
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
public static void main(String args[]) {
Pattern p = Pattern.compile("cool");
Matcher m = p.matcher("Java is cool");
System.out.println("Subsequence: cool");
System.out.println("Sequence: Java is cool");
if (m.find())
System.out.println("
Subsequence found");
else
System.out.println("
Subsequence not found");
}
}輸出
Subsequence: cool Sequence: Java is cool Subsequence found
現在讓我們瞭解一下上面的程式。
在字串序列“Java is cool”中搜索子序列“cool”。然後,使用 find() 方法查詢輸入序列中是否有該子序列,並列印所需的結果。如下面的程式碼片段所示:
Pattern p = Pattern.compile("cool");
Matcher m = p.matcher("Java is cool");
System.out.println("Subsequence: cool" );
System.out.println("Sequence: Java is cool" );
if (m.find())
System.out.println("
Subsequence found");
else
System.out.println("
Subsequence not found");
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP