开发者

JavaScript RegExp: Can I get the last matched index or search backwards/RightToLeft?

开发者 https://www.devze.com 2023-01-27 19:56 出处:网络
Suppose I have a string foo bar baz foo bar baz foo bar baz foo 开发者_如何学Pythonbar baz I want to find for the last occurance of bar, how can I effectively do this? do I need to loop through a

Suppose I have a string

foo bar baz foo bar baz foo bar baz foo 开发者_如何学Pythonbar baz 

I want to find for the last occurance of bar, how can I effectively do this? do I need to loop through add matches? In .NET I can do a RightToLeft search in JS, I guess I can't?


bar(?!.*bar)

will find the last bar in a string:

bar   # Match bar
(?!   # but only if it's not followed by...
 .*   # zero or more characters
 bar  # literal bar
)     # end of lookahead

If your string may contain newline characters, use

bar(?![\s\S]*bar)

instead. [\s\S] matches any character, including newlines.

For example:

match = subject.match(/bar(?![\s\S]*bar)/);
if (match != null) {
    // matched text: match[0]
    // match start: match.index
}

You might also want to surround your search words (if they are indeed words composed of alphanumeric characters) with \b anchors to avoid partial matches.

\bbar\b(?![\s\S]*\bbar\b)

matches the solitary bar instead of the bar within foobar:

Don't match bar, do match bar, but not foobar!
  no match---^     match---^    no match---^


Use the built-in function lastIndexOf:

"foo bar baz foo bar baz foo bar baz foo bar baz".lastIndexOf("bar");

If you want to find the last "word" "bar":

(" "+"foo bar baz foo bar baz foo bar baz foo bar baz"+" ").lastIndexOf(" bar ");
0

精彩评论

暂无评论...
验证码 换一张
取 消