简体   繁体   中英

How to match from the end of the string using regex

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.

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

Using regular expressions

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
}

Using 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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM