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

Lookarounds to the rescue!

^(?!\d+$)\w+$

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


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()]
print(filtered)

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

See another demo on ideone.com.

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

Read more here: Source link