Search code examples
javascriptregexregex-lookarounds

Regex works only with a single words not separated by whitespaces


I have this regex that looks for a digit and a character in a word with a minimum length of 4 :

^(?=.*\d)(?=.*[a-zA-Z])[a-zA-Z0-9]{4,}$ 

it works for :

ABCD1

but if i have multiple words like :

ABCD1 ABCD2

it stop working because the whitespace break the regex :/

How can i improve my regex to allow to capture all the words separated by spaces ?

Demo : https://regex101.com/r/S3APfJ/1


Solution

  • You could use match() on the input to find all matches:

    var input = "1234 ABCD1 ABCD2 ABCDE";
    var matches = input.match(/\b(?=\S*\d)(?=\S*[a-zA-Z])[a-zA-Z0-9]{4,}\b/g);
    console.log(matches);