该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("\nSubsequence found"); else System.out.println("\nSubsequence 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("\nSubsequence found"); else System.out.println("\nSubsequence not found");