Search code examples
pythonpython-3.xregexregex-negation

Getting a correct regex for word starting and ending with different letters


I am quite new to regex and I right now Have a problem formulating a regex to match a string where the first and last letter are different. I looked up on the internet and found a regex that just does it's opposite. i.e. matches words that have same starting and ending letter. Can anyone please help me to understand if I can negeate this regex in some way or can create a new regex to match my requirements. The regex that needs to be modiifed or changed is:

^\s|^[a-z]$|^([a-z]).*\1$

This matches these Strings :

aba,
a,
b,
c,
d,
" ", 
cccbbbbbbac,
aaaaba

But I want it to match strings like:

aaabbcz,
zba,
ccb,
cbbbba

Can anyone please help me in this regard? Thank you.

Note: I will be using this with Python Regex, so the regex should be compataible to be used with Python.


Solution

  • You don't need a regex for this, just use

    s[0] != s[-1]
    

    where s is your string. If you must use a regex, you can use this:

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

    This looks for

    • ^ : beginning of string
    • (.) : a character (captured in group 1)
    • .* : some number of characters
    • (?!\1). : a character which is not the character captured in group 1
    • $ : end of string

    Regex demo on regex101