I’m trying to match a coordinate pair in a String using a Regex in Java. I explicitly want to exclude strings using negative lookahead.
to be matched:
558,228
558,228,
558,228,589
558,228,A,B,C
NOT to be matched:
558,228,<Text>
The Regex ^558,228(?!,<).* does the job, while ^\d{1,},\d{1,}(?!,<).* doesn’t. It’s the same regex with the metacharacter \d instead of values. Any ideas why?
The problem is the
\d{1,}part in combination with the.*at the end.In your case
The
^\d{1,},\d{1,}(?!,<)matches “>558,22” and the.*matches the rest “8,<Text>“You can solve this using the possessive quanitifier
++See it here online on Regexr
\d++is a seldom used possessive quantifier, which is here useful.++means match at least once as many as you can and do not backtrack. That means it will not give back the digits once it has found them.Java Quantifier tutorial