The ‘m‘ flag specifies the regular expression should work in multi line mode. When used with a string containing multiple lines, the '^' and '$' anchors must match both the beginning and end of the string as well as the beginning and end of each line.
let wordPttn = /^(In|On|Upon|With|Within|Out|From|To|Without|About|Above|Below|Of)/mg; let targetString = `Of all the gin joints in all the towns in all the world. Out with the old In with the new. An apple a day keeps the doctor away.From dawn till dusk.To Kill a Mockingbird.The GodFather. \nOn a wing and a prayer.`;let results = targetString.matchAll(wordPttn);for (let result of results) { console.log(result[0]);}
Output:
Of
Out
From
To
On
Try the above example without the 'm' flag. Compare the regex used in the above example with the one used for the same problem but without the 'm' flag.
Find all sentences/phrases that start with ‘The’. Mind you, your regex must match the entire sentence.
let wordPttn = /^The[\s\w]+[.]/mg; let targetString = `The Jackal and the Drum. Of Crows and Owls.The Cunning Mediator.The Foolish Sage. Fighting Goats and the Jackal. \nThe Monkey and the Wedge.`;let results = targetString.matchAll(wordPttn);for (let result of results) { console.log(result[0]);}
Output:
The Jackal and the Drum.
The Cunning Mediator.
The Foolish Sage.
The Monkey and the Wedge.
Find all parts that start with LK and are priced 10.00 or above.
let wordPttn = /^LK[\w ]+[1-9]+[0-9]\.[0-9]{2}$/mg; let targetString = `LK539 6 600 12.00HK353 2 200 20.00SK093 5 500 100.00LK249 10 1000 37.00LK841 2 200 10.00LK139 20 2000 5.00`;let results = targetString.matchAll(wordPttn);for (let result of results) { console.log(result[0]);}
Output:
LK539 6 600 12.00
LK249 10 1000 37.00
LK841 2 200 10.00