该find()
方法在输入序列中找到与所需模式匹配的子序列。在java.util.regex包中可用的Matcher类中可以使用此方法。
给出了一个演示Java正则表达式中Matcher.find()方法的程序,如下所示:
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Demo { public static void main(String args[]) { Pattern p = Pattern.compile("Sun"); Matcher m = p.matcher("The Earth revolves around the Sun"); System.out.println("Subsequence: Sun"); System.out.println("Sequence: The Earth revolves around the Sun"); if (m.find()) System.out.println("\nSubsequence found"); else System.out.println("\nSubsequence not found"); } }
输出结果
Subsequence: Sun Sequence: The Earth revolves around the Sun Subsequence found
现在让我们了解上面的程序。
在字符串序列“地球围绕太阳旋转”中搜索子序列“太阳”。然后,find()
使用该方法查找子序列是否在输入序列中,并打印所需结果。演示此代码段如下:
Pattern p = Pattern.compile("Sun"); Matcher m = p.matcher("The Earth revolves around the Sun"); System.out.println("Subsequence: Sun" ); System.out.println("Sequence: The Earth revolves around the Sun" ); if (m.find()) System.out.println("\nSubsequence found"); else System.out.println("\nSubsequence not found");