如何在输入序列中找到与Java正则表达式所需的模式匹配的子序列?
该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");热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志