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

Viewed 54

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?

2 Answers

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

Seems that the following works:

\b(?!\d+\b|[a-z]+\b)[a-z\d]{4,}\b

Or, if you need case-insensitive:

(?i)\b(?!\d+\b|[a-z]+\b)[a-z\d]{4,}\b

See an online demo


  • \b - A word boundary.
  • (?!\d+\b|[a-z]+\b) - Negative lookahead to prevent either 1+ alpha chars or 1+ digits upto a word-boundary.
  • [a-z\d]{4,}\b - 4+ alphanumeric characters upto a word-boundary.

Edit:

You could also exclude those substrings with an underscore by using another alternative inside the negative lookahead:

\b(?!\d+\b|[a-z]+\b|\w*_)\w{4,}\b
Related