RpTheHotrod
RpTheHotrod

Reputation: 185

Regex - Search for words with letters and numbers with at least 4 characters

I'm trying to find returns such as

hal9
bet97
78test

but not

h4t
4444
test
h1

Essentially, any words with numbers and letters but with a minimum of 4 characters.

Currently I'm trying this for numbers and letters in a word

(?=\w*[a-z])(?=\w*[0-9])\w+

but I'm trying to limit it to 4+ characters only.

Suggestions?

Upvotes: 4

Views: 736

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627292

You can use

\b(?=\w*[A-Za-z])(?=\w*[0-9])\w{4,}\b

See the regex demo.

If \w is Unicode-aware in your regex flavor (e.g. Python re), use

\b(?=\w*[^\W\d_])(?=\w*\d)\w{4,}\b

Also, if your regex flavor supports Unicode property classes and you need to check for any Unicode letter, you can use

\b(?=\w*\p{L})(?=\w*\d)\w{4,}\b

where \p{L} matches any Unicode letter.

Details:

  • \b - word boundary
  • (?=\w*[A-Za-z]) - after any zero or more word chars, there must be a letter
  • (?=\w*[0-9]) - after any zero or more word chars, there must be a digit
  • \w{4,} - four or more word chars (letters, digits, connector punctuation/_)
  • \b - word boundary

Upvotes: 3

Related Questions