贪婪限定符将指定的令牌重复多次,然后引擎回溯,贪婪限定符放弃匹配以最终找到所需的匹配。
正则表达式“(\\ 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));