How do I check if there are different captured characters between two same characters?

Viewed 82

I want to check if a string has the same start and end character and all characters in between are different from the start and end character.

Examples:

  • "abcda" should pass, because it starts and ends with a, and has only non-as in the middle,
  • "abada" should fail, because it not only has a at the start and end, but also in the middle,
  • "bcdefb" should pass — see the first example.

I tried to do it by (.)(?!.*\1)\1, but it failed because there is no length limit, negated end of the string either.

1 Answers

You can use

^(.)(?:(?!\1).)*\1$

See the regex demo. Add (?s) at the start if your string can contain line break chars. Details:

  • ^ - start of string
  • (.) - Group 1: any one char
  • (?:(?!\1).)* - any one char that is not equal to the char captured in Group 1, zero or more times
  • \1 - backreference to the Group 1 value, same char as in the group is required here
  • $ - end of string.

In Java, with String#matches(), you may omit the anchors:

string.matches("(.)(?:(?!\\1).)*\\1")
Related