Selecting Alphanumeric Words Using Regular Expressions

I am trying to find a regex to find only alphanumeric words from a string, i.e. words that are a combination of alphabets or numbers. If the word is pure numbers or pure characters, I need to drop it.

+5
source share
4 answers

Try this regex:

\b([az]+[0-9]+[a-z0-9]*|[0-9]+[az]+[a-z0-9]*)\b 

Or more compact:

 \b([az]+[0-9]+|[0-9]+[az]+)[a-z0-9]*\b 

This matches all words (pay attention to the boundaries of the words \b ) that start with one or more letters, followed by one or more numbers or vice versa, which can be followed by one or more letters or numbers. Thus, the condition of at least one letter and at least one digit is always satisfied.

+6
source

With viewing:

 '/\b(?![0-9]+\b)(?![az]+\b)[0-9a-z]+\b/i' 

A quick test that also shows an example usage:

 $str = 'foo bar F0O 8ar'; $arr = array(); preg_match_all('/\b(?![0-9]+\b)(?![az]+\b)[0-9a-z]+\b/i', $str, $arr); print_r($arr); 

Output:

 F0O 8ar 
+3
source

This will return all individual alphanumeric words that you may skip. I don't think regex can do all the work on its own.

 \b[a-z0-9]+\b 

Make sure you mark this as case insensitive.

0
source
 \b(?:[az]+[0-9]+|[0-9]+[az]+)[[:alnum:]]*\b 
0
source

All Articles