2

Im trying to find regex pattern in java to find if a string includes a 3 letter palindrome like :

    1. goingforeyecheckup
    1. nan means not a number.
Paolo
  • 21,270
  • 6
  • 38
  • 69
learningBird
  • 125
  • 1
  • 1
  • 5

1 Answers1

2

For a three letter palindrome you may use the following pattern:

^(?=.*([a-zA-Z])[a-zA-Z]\1)[a-zA-Z .]+$
  • ^ Assert position beginning of string.
  • (?=.*([a-zA-Z])[a-zA-Z]\1) Positive lookahead. Ensure that at some point in the string there is a letter (([a-zA-Z])), which is followed by a different letter ([a-zA-Z]) and then the same letter again (\1).
  • [a-zA-Z .]+ Character set for letters, whitespace and ., one or more +.
  • $ Assert position end of string.

Regex demo here.


For test strings:

  • goingforeyecheckup Matched because of eye.
  • nan means not a number. Matched because of nan.
  • do not match her Not matched as there is no palindrome.
  • match here Matched because of ere.
Paolo
  • 21,270
  • 6
  • 38
  • 69