0

here is my requirement

const input = 'abcadbca';
const required = 'bca';

the input contains 3 possibility anagrams as:abc,bca,bca; is this all can be selected using regexp? i tried it, but got not result:

const str = 'abcadbca';
const reg = str.match(/(a|b|c)/g);

console.log(reg);

result expectation: [a,b,c,][b,c,a],[b,c,a]; result should be [a,b,c],[b,c,a] - first 2 match are overlapping so first match is taken for the account.

3gwebtrain
  • 14,640
  • 25
  • 121
  • 247

1 Answers1

1

Since you know in advance the characters that constitute the anagrams you're expecting, as indicated by your required constant already consisting of characters b, c and a, you can build a regex with each character included in a sub-pattern that expects it in one of the following 3 characters with a lookahead pattern:

const str = 'abcadbca';
console.log(str.match(/(?=.{0,2}b)(?=.{0,2}c)(?=.{0,2}a).{3}/g));

This outputs:

[
  "abc",
  "bca"
]
blhsing
  • 91,368
  • 6
  • 71
  • 106