Java 正则表达式中 Matcher.group() 方法的作用
java.time.Matcher.group() 方法用于在输入序列字符串中查找与所需模式匹配的子序列。此方法返回匹配上一匹配项(甚至可能是空字符串)的子序列。
下面给出了演示 Java 正则表达式中 Matcher.group() 方法的程序
示例
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
public static void main(String args[]) {
Pattern p = Pattern.compile("\w\d");
Matcher m = p.matcher("This is gr8");
System.out.println("The input string is: This is gr8");
System.out.println("The Regex is: \w\d");
System.out.println();
if (m.find()) {
System.out.println("Match: " + m.group());
}
}
}输出
The input string is: This is gr8 The Regex is: \w\d Match: r8
下面我们来理解一下上述程序。
在字符串序列 "This is gr8" 中搜索子序列 “\w\d”。find() 方法用于查找子序列是否在输入序列中,并使用 group() 方法打印所需的输出。下面一段代码演示了这一点
Pattern p = Pattern.compile("\w\d");
Matcher m = p.matcher("This is gr8");
System.out.println("The input string is: This is gr8");
System.out.println("The Regex is: \w\d");
System.out.println();
if (m.find()) {
System.out.println("Match: " + m.group());
}
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP