Defining regular expressions
If I am defining regular expression using RegExp then I need to add escape character in certain cases.
When I am defining regular expression using RegExp then \w needs to be escaped otherwise it would be
test method is to check if a match is found or not. This method returns true or false.
exec method finds if a match is found or not. It returns an array if a match is found. Otherwise it returns null.
match method acts exactly like exec method if no g parameter is passed. When global flag is turned on the match returns an Array containing all the matches.
Note that in exec the syntax was regex.exec(text) while in match method the syntax is
Now with global flag turned on.
Getting multiple matches
Once again both exec and match method without g option do not get all the matching values from a string. If you want all the matching values then you need to iterate through the text. Here is an example.
Get both the bug numbers in the following case.
Note that in the above case global flag g. Without that above code will run forever.
In the above case match is used instead of regex . However since match with global flag option brings all the matches there was no need to iterate in a loop.
When a match is made then an array is returned. That array has two methods.
index: This tells where in the string match was done
The requirement given to me states that I should strictly look for word
java, ruby or rails within word boundary. This can be done like this.
Above code works. However notice the code duplication. This can be refactored to the one given below.
Above code works and there is no code duplication. However in this case I am asking regular expression engine to create a captured group which I’ll not be using. Regex engines need to do extra work to keep track of captured groups. It would be nice if I could say to regex engine do not capture this into a group because I will not be
?: is a special symbol that tells regex engine to create non capturing group. Above code can be refactored into the one given below.
Share this article:
Subscribe to our monthly newsletter
Thank you! You have successfully subscribed to our newsletter.