Regex works only with a single words not separated by whitespaces

Viewed 43

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

2 Answers

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);

You can use

text.split(/\s+/).filter(x => /YOUR_VALIDATION_REGEX/.test(x))

NOTE:

  • .split(/\s+/) - splits the string with whitespace
  • .filter(x => /^(?=.*\d)(?=.*[a-zA-Z])[a-zA-Z0-9]{4,}$/.test(x) - fetches the item if it matches your initial regex.

See a JavaScript demo:

const text = "this is a phrase with ABC1 and ABCD2 but no ABC1!";
const rx = /^(?=.*\d)(?=.*[a-zA-Z])[a-zA-Z0-9]{4,}$/;
console.log(text.split(/\s+/).filter(x => rx.test(x)));

The /^(?=.*\d)(?=.*[a-zA-Z])[a-zA-Z0-9]{4,}$/ performance can be improved if you use

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