Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find letters in random string exactly, using RegEx

The emphasis here is on the word exactly. This needs to work for any number of permutations, so hopefully my example is clear enough.

Given a string of random letters, is it possible (using RegEx) to match an exact number of letters within the given string?

So if I have a string (str1) containing letters ABZBABJDCDAZ and I wanted to match the letters JDBBAA (str2), my function should return true because str1 contains all the right letters enough times. If however str1 were to be changed to ABAJDCDA, then the function would return false as str2 requires that str1 have at least 2 instances of the letter B.

This is what I have so far using a range:

const findLetters = (str1, str2) => {
  const regex = new RegExp(`[${str2}]`, 'g')
  const result = (str1.match(regex))
  console.log(result)
}

findLetters('ABZBABJDCDAZ', 'JDBBAA')

As you can see it matches the right letters, but it matches all instances of them. Is there any way to do what I'm trying to do using RegEx? The reason I'm focusing on RegEx here is because I need this code to be highly optimised, and so far my other functions using Array.every() and indexOf() are just too slow.

Note: My function only requires to return a true/false value.

like image 711
Joss Classey Avatar asked May 17 '26 09:05

Joss Classey


1 Answers

Try (here we sort letters of both strings and then create regexp like A.*A.*B.*B.*D.*J)

const findLetters = (str1, str2) => {
  const regex = new RegExp([...str2].sort().join`.*`)
  return regex.test([...str1].sort().join``)
}

console.log( findLetters('ABZBABJDCDAZ', 'JDBBAA') );
console.log( findLetters('ABAJDCDA', 'JDBBAA') );
like image 109
Kamil Kiełczewski Avatar answered May 20 '26 00:05

Kamil Kiełczewski