该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("the"); Matcher m = p.matcher("eclipses of the sun and the moon"); System.out.println("Subsequence: the"); System.out.println("Sequence: eclipses of the sun and the moon"); System.out.println(); while (m.find()) { System.out.println("the found at index " + m.start()); } } }
输出结果
Subsequence: the Sequence: eclipses of the sun and the moon the found at index 12 the found at index 24
现在让我们了解上面的程序。
在字符串序列“日月食”中搜索子序列“ the”。然后,该find()
方法用于查找子序列是否在输入序列中任意次,并打印出所需的结果。演示此代码段如下:
Pattern p = Pattern.compile("the"); Matcher m = p.matcher("eclipses of the sun and the moon"); System.out.println("Subsequence: the" ); System.out.println("Sequence: eclipses of the sun and the moon" ); System.out.println(); while (m.find()) { System.out.println("the found at index " + m.start()); }