Java 正则表达式中的贪婪限定符
贪婪限定符尽可能重复指定令牌,然后引擎回溯,贪婪限定符放弃匹配以最终找到所需匹配。
正则表达式 "(\w+)(\d)(\w+)" 用于在字符串 "EarthHas1Moon" 中查找匹配。
如下所示演示此功能的程序
示例
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
public static void main(String args[]) {
String str = "EarthHas1Moon";
String regex = "(\w+)(\d)(\w+)";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
m.find();
System.out.println(m.group(1));
System.out.println(m.group(2));
System.out.println(m.group(3));
}
}输出
EarthHas 1 Moon
现在让我们了解上面的程序。
正则表达式为“(\w+)(\d)(\w+)”。在字符串序列 "EarthHas1Moon" 中搜索该表达式。find() 方法用于查找正则表达式是否在输入序列中,并打印所需的结果。演示此功能的代码片段如下
String str = "EarthHas1Moon"; String regex = "(\w+)(\d)(\w+)"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(str); m.find(); System.out.println(m.group(1)); System.out.println(m.group(2)); System.out.println(m.group(3));
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP