regexp: It is a required parameter, and it is a value to search for, as a regular expression.
// app.js let str = "Here is your winner, brock lesnar"; let res = str.match(/bro/gi); console.log(res);
node app [ 'bro' ]
In this example, we are checking bro string against the main string, and it found the match and returns the array containing that item.
Global search in regex
To search global in the string using regex, use match() method and pass “g” flag.
// app.js let str = "Well done brock! Well done"; let res = str.match(/Well/g); console.log(res);
node app [ 'Well', 'Well' ]
In this example, we are searching globally for a Well pattern, and it finds two times in the string. Here “g” flag suggests that the regular expression should be tested against all possible matches in the string.
Python regex match: case-sensitive
If you don’t pass the case sensitivity flag “i” explicitly, then it will return null. By default, the string match() method does not check case sensitive match. If you want to check a case-sensitive match, then you have to pass “i” flag explicitly.
// app.js let str = "Well done brock! Well done"; let res = str.match(/well/g); console.log(res);
Our pattern is well, and our input string contains Well. So, there is a mismatch between the input string and pattern. That is why it returns null.
If you pass the “i” flag in the regex, then it will return true.
// app.js let str = "Well done brock! Well done"; let res = str.match(/well/gi); console.log(res);
[ 'Well', 'Well' ]
Here “i” flag helps to find the case-sensitive match in the given string.
If the regex doesn’t have flag g, then it returns the first match as an array.
If the regex has flag g, then it returns the array of all matches as strings.
If there are no matches found using match() method, no matter if there’s flag g or not, the null is returned.