Regex: How to not match the last character of a word?

10,346

If you are using a negative lookahead, you could put it at the beginning:

(?![a-z]*:)[a-z]+

i.e: "match at least one a-z char, except if the following chars are 0 to n 'a-z' followed by a ':'"

That would support a larger regex:

 X(?![a-z]*:)[a-z]+Y

would match in the following string:

 Xeee Xrrr:Y XzzzY XfffZ

only 'XzzzY'

Share:
10,346
Callum Rogers
Author by

Callum Rogers

I am interested in Functional Programming, Compilers, Programming Languages, Interpreters and Reactive Programming. Github

Updated on September 12, 2022

Comments

  • Callum Rogers
    Callum Rogers over 1 year

    I am trying to create a regex that does not match a word (a-z only) if the word has a : on the end but otherwise matches it. However, this word is in the middle of a larger regex and so I (don't think) you can use a negative lookbehind and the $ metacharacter.

    I tried this negative lookahead instead:

    ([a-z]+)(?!:)
    

    but this test case

    example:
    

    just matches to

    exampl
    

    instead of failing.

  • Tim Pietzcker
    Tim Pietzcker over 14 years
    And what about a word that is followed by punctuation other than ":"?
  • Harish
    Harish over 14 years
    Sorry my fault! I forgoted it.