如何在输入序列中找到与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 婆婆66岁祝福语简短
13 今天孩子高考祝福语简短
14 送彩票生日祝福语简短
15 分别祝福语简短情话英文
16 画室揭牌仪式祝福语简短
17 女友妈妈生日祝福语简短
18 离别赠言离职祝福语简短