简体   繁体   English

排除模式为“xyyx”的单词,但包括以相同字母开头和结尾的单词

[英]Exclude words with pattern 'xyyx' but include words that start & ends with same letter

I have a regex to match words that starts and ends with the same letter (excluding single characters like 'a', '1' )我有一个正则表达式来匹配以相同字母开头和结尾的单词(不包括像 'a', '1' 这样的单个字符)

(^.).*\1$

and another regex to avoid matching any strings with the format 'xyyx' (eg 'otto', 'trillion', 'xxxx', '-[[-', 'fitting')和另一个正则表达式,以避免匹配任何格式为'xyyx'的字符串(例如'otto'、'trillion'、'xxxx'、'-[[-'、'fitting')

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

How do I construct a single regex to meet both of the requirements?如何构建单个正则表达式来满足这两个要求?

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.但请注意将最后一个模式的反向引用更改为\3 ,因为前瞻已经使用组 1 和组 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.也匹配一个空格,所以如果你不想匹配空格,你可以使用\S来匹配非空白字符。

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

Regex demo正则表达式演示

I would place the negative look-ahead after the initial character let it exclude the final character (as those two should be part of a positive capture):我会在初始字符之后放置负前瞻,让它排除最终字符(因为这两个应该是捕获的一部分):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM