我了解到Java正则表达式需要编译才能在字符串上进行任何类型的正则表达式匹配,但我不明白为什么需要编译。
正则表达式字符串编译后会生成更高效的表示方式,比String类型更高效。那编译后的表示方式是什么?它是如何比String类型更高效的?
我了解到Java正则表达式需要编译才能在字符串上进行任何类型的正则表达式匹配,但我不明白为什么需要编译。
正则表达式字符串编译后会生成更高效的表示方式,比String类型更高效。那编译后的表示方式是什么?它是如何比String类型更高效的?
public static void main(String[] args){
// using "string representation"
System.out.println("some string".matches("myRegex"));
// using "compiled representation"
Pattern myPattern = Pattern.compile("myRegex");
Matcher myMatcher1 = myPattern.matcher("some string 1");
Matcher myMatcher2 = myPattern.matcher("some string 2");
System.out.println(myMatcher1.matches());
System.out.println(myMatcher2.matches());
}
但是如果你看一下"some string".matches("myRegex")
所使用的方法,你会发现它也调用了Pattern.compile()
来翻译正则表达式指令:
String.java
public boolean matches(String regex) {
// return Pattern.matches(regex, this);
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
return m.matches();
}
因此,使用“字符串表示法”仍会编译RegEx,只是不会缓存模式以供重复使用。
/\d\s_/
变成状态和转换,然后开始消耗字符:“1_”->抓取“1”->好的,匹配\d
->移动到下一个状态->抓取空格->好的,匹配\s
->移动到下一个状态->抓取“_”->好的,匹配_
->完成。如果提供“1a_”,则抓取“1”->好的,匹配\d
->移动到下一个状态->抓取“a”->不匹配\s
->结束。 - VLAZ