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?
Edit: 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})?$).*";
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With