在 Java 中使用 find() 来查找多个子序列
find() 方法在输入序列中查找与所需模式匹配的多个子序列。该方法可在 Matcher 类中找到,而 Matcher 类可在 java.util.regex 包中找到
下面是一个在 Java 中使用 find() 方法查找多个子序列的程序
示例
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
现在,让我们来了解一下上面的程序。
在字符串序列“eclipses of the sun and the moon”中搜索子序列“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()); }
广告