使用Pattern类在Java中进行匹配
正则表达式的表示形式在java.util.regex.Pattern类中可用。此类基本上定义了正则表达式引擎使用的模式。
给出了一个演示如何使用Pattern类在Java中进行匹配的程序,如下所示-
示例
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
public static void main(String args[]) {
Pattern p = Pattern.compile("p+");
Matcher m = p.matcher("apples and peaches are tasty");
System.out.println("The input string is: apples and peaches are tasty");
System.out.println("The Regex is: p+ ");
System.out.println();
while (m.find()) {
System.out.println("Match: " + m.group());
}
}
}输出结果
The input string is: apples and peaches are tasty The Regex is: p+ Match: pp Match: p
现在让我们了解上面的程序。
在字符串序列“苹果和桃子好吃”中搜索子序列“p+”。Pattern类定义正则表达式引擎使用的模式,即“p+”。该find()方法用于查找子序列(即p后跟任意数量p的子序列)是否在输入序列中,并且是否打印了所需的结果。演示这的代码片段如下-
Pattern p = Pattern.compile("p+");
Matcher m = p.matcher("apples and peaches are tasty");
System.out.println("The input string is: apples and peaches are tasty");
System.out.println("The Regex is: p+ ");
System.out.println();
while (m.find()) {
System.out.println("Match: " + m.group());
}热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短