javaregexstring

Java pattern matching for validation


I need to validate a String. Ex: AABCAd. In this string 'A' can occur n number of times. But continuously it can occur only twice not more than that. Example for invalid string is AAAXCA. Since it occurred more than 2 times continuously. I need to validate the string using pattern matching. Please provide help.


Solution

  • Use a negative lookahead at the start for checking the appearance of A in a string.

    "^(?!.*AAA)\\w+$"
    

    (?!.*AAA) negative lookahead asserts that the string going to be match won't contain atleast three consecutive A's.

    DEMO