正则表达式的表示形式在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());

}


版权声明:本文为weixin_35473217原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_35473217/article/details/114506209