Jakarta Regexp和Java 6 java.util.regex之间的区别

时间:2023-01-07 14:06:23

I am in the process of migrating from Jakarta Regexp to the standard Java 6 regular expressions package java.util.regex. I noticed the following difference when not specifying the beginning ^ and end $ in a regexp: Jakarta Regexp returns true when the regexp matches part of the string, while the Java 6 java.util.regex package does not:

我正在从Jakarta Regexp迁移到标准的Java 6正则表达式包java.util.regex。我没有在regexp中指定开头^和end $时注意到以下区别:当regexp匹配部分字符串时,Jakarta Regexp返回true,而Java 6 java.util.regex包不返回:

String regexp = "\\d";
String value = "abc1abc";

Pattern pattern = Pattern.compile(regexp);
Matcher matcher = pattern.matcher(value);
result = matcher.matches(); // returns false

Returns false whereas:

返回false而:

RE re = new RE(regexp);
re.match(value); // returns true

Returns true.

What is the reason behind this? I've thought about greedy/lazy matching but that doesn't seem to be relevant in the case of JDK 6 not matching.

这背后的原因是什么?我已经考虑过贪婪/懒惰匹配,但在JDK 6不匹配的情况下似乎没有相关性。

Are there any other differences that I should be aware of?

我应该注意哪些其他差异?

2 个解决方案

#1


5  

The java.util.regex.Matcher.matches() method will try to match the complete input string against your regular expression which will be false.

java.util.regex.Matcher.matches()方法将尝试将完整的输入字符串与正则表达式匹配,这将是false。

If you want to search for the pattern in the input string, you'll need to use java.util.regex.Matcher.find() method instead:

如果要在输入字符串中搜索模式,则需要使用java.util.regex.Matcher.find()方法:

 result = matcher.find(); // returns true

#2


2  

Use find() instead of matches(). It functions exactly as you are expecting.

使用find()而不是matches()。它的功能与您期望的完全相同。

#1


5  

The java.util.regex.Matcher.matches() method will try to match the complete input string against your regular expression which will be false.

java.util.regex.Matcher.matches()方法将尝试将完整的输入字符串与正则表达式匹配,这将是false。

If you want to search for the pattern in the input string, you'll need to use java.util.regex.Matcher.find() method instead:

如果要在输入字符串中搜索模式,则需要使用java.util.regex.Matcher.find()方法:

 result = matcher.find(); // returns true

#2


2  

Use find() instead of matches(). It functions exactly as you are expecting.

使用find()而不是matches()。它的功能与您期望的完全相同。