-1

I am trying to implement custom regular expressions in my Java program to verify if my input string matches the regex. But for some reason, the regex fails at a particular point even though the input string matches it.

String input = "abc:def:id:identifier:123456.890123.1";
System.out.println(input.matches("(abc:def:id:identifier:).[0-9]{6,12}.[0-9]{1,6}.[0-9]{1,20}"));

The regex returns false at the point 123456 even though the input matches the length of 6. If I give 1234567 then it would return true. I am wondering why it fails for 123456 even though it matches the length. Also, it does not fail for the next one where I have just 1 and length of {1,20}.

Also, is there a better way to verify this string in regex or this is a good and efficient way?

BATMAN_2008
  • 2,788
  • 3
  • 31
  • 98
  • 2
    Your use of the dot (any character other than newline) is messing things up. You want to escape it using `\.`. Also I don't see a dot in your input after the colon, so you probably want to ditch that one. – JvdV Feb 05 '21 at 08:29
  • Thanks a lot this worked: `input.matches("(abc:def:id:identifier:)[0-9]{6,12}\\.[0-9]{1,6}\\.[0-9]{1,20}")`. Also, one more doubt is this the only way to verify or there is a better way to verify the pattern in my input using regex? Any other better technique to validate the same. – BATMAN_2008 Feb 05 '21 at 08:33
  • @JvdV Please add this as the answer. – Dale Feb 05 '21 at 08:35

1 Answers1

-1

As mentioned by @JvdV, should remove . at the start which is causing the problem during the validation.

Following should work:

input.matches("(abc:def:id:identifier:)[0-9]{6,12}\\.[0-9]{1,6}\\.[0-9]{1,20}")
BATMAN_2008
  • 2,788
  • 3
  • 31
  • 98