const regex = /['"]([ \w]+)?MATCH([ \w]+)?["']/mg;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('[\'"]([ \\w]+)?MATCH([ \\w]+)?["\']', 'mg')
const str = `I have a string like get(3,"No MATCH",obj). I want to check if the word MATCH is enclosed within quotes (either single quote or double quote). Here MATCH is enclosed within quotes, although not exactly as "MATCH", it is still a part of the text contained in quotes as "No MATCH".
I want to write a function which takes the word (MATCH) as argument and returns true if it is contained within quotes or false if not.
Following are some other input strings which needs to be checked by this function:
* get(1101,"MATCH",obj) --> return true since MATCH is within quotes
* get(255,'NO MATCH',obj) --> return true since MATCH is a part of text contained within quotes
* get(1111,"" , MATCH) ---> return false since MATCH is not contained within quotes`;
// Reset `lastIndex` if this regex is defined globally
// regex.lastIndex = 0;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions