使用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("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());
}热门推荐
10 祝孙辈生日祝福语简短
11 恋人跨年祝福语大全简短
12 考大学敬酒简短祝福语
13 开工投产大吉祝福语 简短
14 偶然结婚祝福语朋友简短
15 感谢学长学姐祝福语简短
16 戏精的祝福语简短
17 我要结婚祝福语简短
18 婚前女儿生日祝福语简短