JS Regular Expressions: Specify Upper and Lower Number of Matches Passed

In tutorial

Regular Expressions: Specify Upper and Lower Number of Matches Passed

Quote the tutorial::
For example, to match only the letter a appearing between 3 and 5 times in the string "ah" , your regex would be /a{3,5}h/ .

let A4 = "aaaah";
let A2 = "aah";
let multipleA = /a{3,5}h/;
multipleA.test(A4); // Returns true
multipleA.test(A2); // Returns false

Questions :
let A7 = “aaaaaaah”;
Why multipleA.test(A7) also returns ture? Shouldn’t it return false because it exceed 5 ‘a’ ?

let A7 = "aaaaaaah";
            12345

5 “a” characters followed by an “h” anywhere in the string. The two other “a” characters at the start don’t have any relevance in this match

compare

/^a{3,5}h/.test("aaaaaaah") // false

/a{3,5}.test("aaaaaaah") // true

The first regex matches: ^ (start of string), a{3,5} (between 3 and 5 “a” characters), then one “h” character. So there are not between 3 and 5 “a” characters followed by an “h” at the start of the string (there are 5 followed by another “a”).

The second regex matches a{3,5} (between 3 and 5 “a” characters), then one “h” character. Two characters into the string we get a match (5 “a” characters followed by an “h”).

1 Like