How to write a Python regex that matches strings with both words and digits, excluding digits-only strings?

Lookarounds to the rescue!


This uses a negative lookahead construct and anchors, see a demo on

Note that you could have the same result with pure Python code alone:

samples = ["expression123", "123expression", "exp123ression", "1235234567544"]
filtered = [item for item in samples if not item.isdigit()]

# ['expression123', '123expression', 'exp123ression']

See another demo on

With both approaches you wouldn’t account for input strings like -1 or 1.0 (they’d be allowed).

Read more here: Source link