Home > front end >  Exclude words with pattern 'xyyx' but include words that start & ends with same letter
Exclude words with pattern 'xyyx' but include words that start & ends with same letter

Time:02-05

I have a regex to match words that starts and ends with the same letter (excluding single characters like 'a', '1' )

(^.).*\1$

and another regex to avoid matching any strings with the format 'xyyx' (e.g 'otto', 'trillion', 'xxxx', '-[[-', 'fitting')

^(?!.*(.)(.)\2\1)

How do I construct a single regex to meet both of the requirements?

CodePudding user response:

You can start the pattern with the negative lookahead followed by the pattern for the match. But note to change the backreference to \3 for the last pattern as the lookahead already uses group 1 and group 2.

Note that the . also matches a space, so if you don't want to match spaces you can use \S to match non whitespace chars instead.

^(?!.*(.)(.)\2\1)(.).*\3$

Regex demo

CodePudding user response:

I would place the negative look-ahead after the initial character, and let it exclude the final character (as those two should be part of a positive capture):

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

Note that the negative check concerns characters between the start and ending character, and so these words would not be rejected:

oopso
livewell
  •  Tags:  
  • Related