Reputation:
Im not good in regular exp, i want to match a string begginning from the end of the other string.
var keyword = new Array();
keyword[0] = " void main";
var pool1 = "abdodfo void main";
var pool2 = "abdodfo void main a";
var pool3 = "abdodfo void main ab void mai";
What will be the right regex in the control struct to satisfy the ff:
*should match
if(pool1.match(keyword[0]))
*should NOT match
if(pool2.match(keyword[0]))
if(pool3.match(keyword[0]))
I made this code simpler, i will use this for syntax checking error of my c++ IDE project.
Upvotes: 1
Views: 125
Reputation: 715
The $
symbol denotes the end of a string:
var test = " void main";
var matches = test.match(/main$/); // returns an array of matches, in this case ["main"]
if (matches.length > 0) {
// do stuff
}
slice()
In this particular case, you could also use the slice()
function, which might be simpler:
var test = " void main";
if (test.slice(-4) === "main") {
// do stuff
};
A link to MDN's documentation on slice()
.
Upvotes: 1
Reputation: 369424
Use $
to denote end of the input string:
/ void main$/
var pattern = / void main$/;
var pool1 = "abdodfo void main";
var pool2 = "abdodfo void main a";
var pool3 = "abdodfo void main ab void mai";
console.log(pattern.test(pool1)); // => true
console.log(pattern.test(pool2)); // => false
console.log(pattern.test(pool3)); // => false
Upvotes: 5