Regex to match all lowercase character except some words

Viewed 737

I would like to write a RE to match all lowercase characters and words (special characters and symbols should not match), so like [a-z]+ EXCEPT the two words true and false.

I'm going to use it with Python.

I've written (?!true|false\b)\b[a-z]+, it works but it does not recognise lowercase characters following an uppercase one (e.g. with "This" it doesn't match "his"). I don't know how to include also this kind of match.

For instance:

  • true & G(asymbol) & false should match only asymbol
  • true & G(asymbol) & anothersymbol should match only [asymbol, anothersymbol]
  • asymbolUbsymbol | false should match only [asymbol, bsymbol]

Thanks

2 Answers

You will need to remove \b (word boundary) and use a negative lookbehind in your regex as this:

(?<![a-z])(?!true|false)[a-z]+

RegEx Demo

RegEx Details:

  • (?<![a-z]): Assert that we don't have a lowercase letter at the left
  • (?!true|false): Assert that we don't have true or false at the right
  • [a-z]+: Match 1+ lowercase characters

I would create two regexes (you want to mix word boundary matching with optionally splitting words apart, which is, AFAIK not straighforward mixable, you would have to re-phrase your regex either without word boundaries or without splitting):

  • first regex: [a-z]+
  • second regex: \b(?!true|false)[a-z]+
Related