How can I find the last occurrence of a word with word boundaries? I created a regex expression of /\btotal\b/
for the word. How would I use search() to find the last occurrence of this expression? Thanks in advance for the help!
You can use negative lookahead to get the last match:
/(\btotal\b)(?!.*\b\1\b)/
(?!.*\\1)
is negative lookahead to assert that captured group #1 ie total
word is NOT present ahead of the present match.
Without using the lookaheads but using the same regex (having applied the g
, ie global, flag), the option would be to match the string with regex and get the last match.
var matches = yourString.match(/\btotal\b/g);
var lastMatch = matches[matches.length-1];
I like @anubhava's answer. And in case your string might contain line breaks, you can try the following Negative Lookahead:
(\btotal\b)(?!.*[\r\n]*.*\1)
See an example on regex101. Also see below, we replace the last occurrence of total
with <TOTAL>
var str = `
something total abc
total
foo total anything here
total
Anything total done!
`;
var finalStr = str.replace(/(\btotal\b)(?!.*[\r\n]*.*\1)/, "<TOTAL>");
console.log(finalStr)
And you will get:
something total abc
total
foo total anything here
total
Anything <TOTAL> done!
@anubhava answer is correct for single line inputs, but the idea is correct thank you for sharing it!
I think his answer can be improved (but please do correct me if I'm wrong) with version below:
/\b(total)\b(?![\s\S]*\b\1\b)/
The difference here is that [\\s\\S]*
will effectively match any character , new lines included. Also word boundary \\b
are not really needed in the capturing group.
In the linked 2nd example by @anubhava it's matching only the very first total
word found because the pattern (?!.*\\b\\1\\b)
will not consider newlines. You can verify by adding the word total
somewhere at the beginning of the sample mail text.
Demo link: https://regex101.com/r/VlhRWM/3
I'm just a bit worried about performance of the [\\S\\s]*
pattern.
Also I think that the reported errors in comments, for not found matching group, are related to the regex ECMAScript flavor selected in the linked demo, using PCRE is reporting correctly the match.
NB.
This pattern will consider a valid match in the ENTIRE input provided. If you need a per line match, you need to enable the /g
global flag and use @anubhava answer!
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.