java - Unexpected regular expression behavior using Positive Lookbehind -


i writing regular expression match sequence of digits, followed dot , sequence of digits, , in total length, including dot, entire sequence should 13. purpose, regular expression wrote was: (\d{6,12})\.(\d{0,6})(?<=.{13})

when run expression against 2 following samples of data, expecting second 1 match, instead, both mathed. can me understand why?

  • 1234567.123456 > matched expecting not matched;
  • 1234567.12345 > matched.

here java code used test this: import java.util.regex.pattern;

public class app {     public static void main(string[] args) {         pattern matcher = pattern.compile("(\\d{6,12})\\.(\\d{0,6})(?<=.{13})");         system.out.println(matcher.matcher("1234567.123456").matches());         system.out.println(matcher.matcher("1234567.12345").matches());     } } 

output:

true true 

you need anchor lookbehind assertion start of string, or match substring:

pattern matcher = pattern.compile("(\\d{6,12})\\.(\\d{0,6})(?<=^.{13})"); 

or use lookahead assertion instead (easier understand, imo):

pattern matcher = pattern.compile("(?=.{13}$)(\\d{6,12})\\.(\\d{0,6})"); 

Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -