1
let sampleWord = "mA11";
let match1 = /(?=\w{4,6})(?=\D\d{2})/;
let match2 = /(?=\w{4,6})/;
let match3 = /(?=\D\d{2})/;

console.log(match1.test(sampleWord));
console.log(match2.test(sampleWord));
console.log(match3.test(sampleWord));

Here's the console output:

// console output
false
true
true

Here's my regex code. My confusion is the first part /?=\w{4,6}/ This means a string of character 4 to 6. and the second part (?=\D\d{2}) This means anystring that has one non digit character in the beginning and two consecutive digits. so How is 'mA11' not matching /(?=\w{4,6})(?=\D\d{2})/; it's of length 4 and a11 also satisfies the second condition. And how is the 'mA111' string matching the match1 condition? This also satisfies for strings more than length 6 which I don't know how?

NobinPegasus
  • 545
  • 2
  • 16
  • 1
    `(?=\w{4,6})(?=\D\d{2})` means that you want the next 4 chars to be word chars, and *at the same time*, the next char must be a non-digit and the second and third ones must be digits. There is no such a substring in the input text. [Lookarounds "stand their ground".](https://www.rexegg.com/regex-lookarounds.html#stand_their_ground) – Wiktor Stribiżew Jan 31 '23 at 08:40
  • Then how come **mA111** returns true? – NobinPegasus Jan 31 '23 at 08:44
  • 1
    `A111` matches your unanchored pattern. Anchor it (`/^(?=\w{4,6})(?=\D\d{2})/`), and there will be no match. – Wiktor Stribiżew Jan 31 '23 at 08:46
  • So why doesn't the unanchored match work in the case of `mA11` Here it can also match `A11` As the matching cursor stands in the first index and it checks mA1 in case of **mA11** shouldn't it do the same for the case of **mA111** and try to match `mA1` as the index stays in the first position always? – NobinPegasus Jan 31 '23 at 08:53
  • 1
    There is no way to match `A11`, you require at least 4 chars to appear immediately to the right of the current location in `(?=\w{4,6})`. – Wiktor Stribiżew Jan 31 '23 at 08:56

0 Answers0