在 Java 中使用 Pattern 类进行匹配
正则表达式的表示方式可在 java.util.regex.Pattern 类中找到。此类基本上定义了正则引擎所使用的模式。
以下是一个演示在 Java 中使用 Pattern 类进行匹配的程序 −
示例
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
现在,我们来理解一下上面的程序。
在字符串序列"apples and peaches are tasty"中搜索子序列“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());
}
广告
数据结构
联网
RDBMS
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP