From below list we need to find all word that start with ‘b’ and end with ‘r’. So we should get ‘br’, ‘bar’, ‘baar’, ‘ber’, ‘bear’.
const str = 'fo br bar baar ber bear foo';
Lets start with simple regular expression where we will use the opening and closing square brackets of regular expression as below:-
str.match(/b[a]r/g); // Output ['bar']
No what we expected but a good start. Now let’s add a ‘+’ which will help capture one and more occurrences of ‘a’. So out new expression will be:-
str.match(/b[a]+r/g); // Output ['bar', 'baar']
Ok but ‘br’ is still missing let see what we can do. We can replace the ‘+’ with ‘*’ as it will get zero and more occurrence compare to ‘+’ which gives one and more.
str.match(/b[a]*r/g); // Output ['br', 'bar', 'baar']
So not let’s focus on ‘ber’ and ”bear” part. We canadd ‘e’ with inside the square brackets so the regular expression will search for ‘e’ as well. So after adding ‘e’ voila we get our desired output.
str.match(/b[ae]*r/g); // Output ['br', 'bar', 'baar', 'ber', 'bear']