简体   繁体   中英

regex matches in rubular, not in java

Im having problems getting some regex expressions to work using java.util.regex's pattern matchers. I have the following expression:

(?=^.{1,6}$)(?=^\d{1,5}(,\d{1,3})?$)

i test matches against the following strings:

12345  (match OK)
123456 (no match)
123,12 (match OK)

When i test it out on the following sites it seems to work perfectly:

http://rubular.com , ok

http://www.regextester.com/ , ok

http://myregextester.com/index.php , ok

However i cant seem to get it to match anything in my java program. Also, an online java regex tester gives the same result (no matches) :

http://www.regexplanet.com/advanced/java/index.html No matches ???

I don't have a clue why i can't get this to work in java, but seems to work in a lot of other regex engines?

this was the non-working code. 这是非工作代码。 Excuse typo's , i cant copy/paste from my code-pc to stackoverflow.

String inputStr = "12345";
String pattern = "(?=^.{1,6}$)(?=^\\d{1,5}(,\\d{1,3})?$)";
Pattern regexp = Pattern.compile(pattern);
System.out.println("Matches? "+regexp.matcher(inputStr).matches());
System.out.println(inputStr.matches(pattern));

First of all you need to escape the \\ s in the pattern. Then if you use matches() , Java tries to match against the entire string, so it will return false unless you either remove the second lookahead or add a .* at the end.

This produces the right output in Java:

    String regex = "(?=^.{1,6}$)^\\d{1,5}(,\\d{1,3})?$";
    System.out.println("12345".matches(regex)); 
    System.out.println("123456".matches(regex)); 
    System.out.println("123,12".matches(regex));

And so does this expression:

    String regex = "(?=^.{1,6}$)(?=^\\d{1,5}(,\\d{1,3})?$).*";

The difference between the tools is, that in one case it tries to find a match in the other it tries to match the whole string. If you use string.matches(regex) in java, this will return false for all of your inputs as you do not match the whole string with your lookahead expression. Either you append a .* as Keppil suggests, or you use the Matcher class:

Pattern p = Pattern.compile(regex);
Matcher matcher = p.matcher(text);
if(matcher.find()) {
    System.out.println("Match found");
}

It's working correctly. You're probably using the matches() method, which expects the regex to match and consume the whole string. Your regex doesn't consume anything because it's just a couple of lookaheads. On the RegexPlanet site, look at the find() column and you'll see the results you expect. In your Java code, you have to create a Matcher object so you can use its find() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM