How can I use regex to find an exact match in a string?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can use regular expressions (regex) to find an exact match in a string by putting your desired pattern between a slash (“/”) and adding gm flags. The ‘g’ mean it’ll find all matches, not just first. ‘m’ for multiline.
Lets say we’re looking for word “apple” in a text, you’d do something like this in, say, JavaScript:
“`javascript
var text = “I have an apple. I like apple.”;
var regex = /apple/gm;
var match = text.match(regex);
“`
“match” will now be array containing all instances of “apple”.
The above code will match “apple” in any context – for example, it’d find the “apple” in “pineapple”.
To ensure exact match, you could add word boundary markers (“\b”) to pattern to say that the match must start and end with a word boundary. (word boundary being the start/end of the string, or any white space character):
“`javascript
var text = “I have a pineapple. I like apple.”;
var regex = /\bapple\b/gm;
var match = text.match(regex);
“`
“match” will now only contain the “apple” that stands alone.
You see, regex can be very powerful for string manipulation once you get the hang of it. Don’t afraid to experiment with them.