Home > other >  Using regex to check for no characters before another
Using regex to check for no characters before another

Time:06-06

I am trying to select any letter character (a-z) with no numbers in front of it. For example:

2x a-3p returns a
a b-c d returns a,b,c,d
7g 8k returns nothing

I'm attempting to use regex for this so that I can use the expression in python but I can't find the solution.

I am using Python 3.10.4 if that is necessary.

CodePudding user response:

You may need a negative lookbehind:

(?<!\d)[a-z]

Translates exactly into "any letter character (a-z) with no numbers in front of it".

Check the demo here.

CodePudding user response:

A first pass attempt would be

p = re.compile(r'[^0-9]([a-z])')

This would get a lower-case letter preceded by a character which is not a digit. However, You would miss any letters which occurred at the beginning of a line since there would be no character preceding the letter. So, you can instead do

p = re.compile(r'(?:[^0-9]|^)([a-z])')
  • Related