问题描述
假设我有一个字符串
foo bar baz foo bar baz foo bar baz foo bar baz
我想找到最后一次出现的酒吧,我该怎样才能有效地做到这一点?我需要循环添加匹配吗?在.NET中,我可以在JS中进行RightToLeft搜索,我想我不能?
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)
会找到最后一个 bar
in a string:
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)
。 [\\\\ S]
匹配任何字符,包括换行符。
instead. [\s\S]
matches any character, including newlines.
例如:
match = subject.match(/bar(?![\s\S]*bar)/);
if (match != null) {
// matched text: match[0]
// match start: match.index
}
您可能还想用 \围绕搜索词(如果它们确实是由字母数字字符组成的单词) b
锚点以避免部分匹配。
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)
匹配单独的 bar
而不是中的
:栏
foobar
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---^
这篇关于JavaScript RegExp:我可以获取最后匹配的索引或向后搜索/ RightToLeft吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!