正则表达式查找字符串上的最后一个标记
我想知道是否有一种方法可以
var string = "foo::bar"
仅使用正则表达式来获取字符串的最后一部分: "bar"
。
我试图进行预测,但无法充分掌握它们来做到这一点。
--
更新
也许一些例子会让问题更清楚。
var st1 = "foo::bar::0"
match should be 0
var st2 = "foo::bar::0-3aab"
match should be 0-3aab
var st3 = "foo"
no match should be found
I was wondering if there is a way having this
var string = "foo::bar"
To get the last part of the string: "bar"
using just regex.
I was trying to do look-aheads but couldn't master them enough to do this.
--
UPDATE
Perhaps some examples will make the question clearer.
var st1 = "foo::bar::0"
match should be 0
var st2 = "foo::bar::0-3aab"
match should be 0-3aab
var st3 = "foo"
no match should be found
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用负前瞻:
结果将出现在捕获中。
另一种方法:
这应该可行,因为
.*
贪婪地匹配,因此::
将匹配该字符串的最后出现。You can use a negative lookahead:
The result will then be in the capture.
Another approach:
This should work because the
.*
matches greedily, so the::
will match the last occurence of that string.简而言之,
除非您确切知道要匹配的字符串有多长,否则您不能使用前瞻。幸运的是,这不是问题,因为您只查看字符串
$
的末尾。Simply,
You can't use lookaheads unless you know exactly how long a string you're trying to match. Fortunately, this isn't an issue, because you're only looking at the end of the string
$
.我不会为此使用正则表达式(尽管你当然可以);我将在
::
上拆分字符串,因为从概念上讲这就是您想要做的。如果您确实只需要正则表达式,可以使用
/::((?:[^:]|:(?!:))*)$/
。首先,它匹配文字::
。然后,我们使用括号将所需的内容放入捕获组 1 中。所需的内容是(?:...)
括号内的字符串的一个或多个副本;此包围组无需捕获。然后,我们查找[^:]
(非冒号字符)或:(?!:)
(冒号后跟非冒号)。(?!...)
是负向先行,仅当下一个标记不与所包含的模式匹配时才匹配。由于 JavaScript 不支持负向后查找,因此我找不到避免捕获::
的好方法,但您可以将其包装在函数中:I wouldn't use regular expressions for this (although you certainly can); I'd split the string on
::
, since that's conceptually what you want to do.If you really want just a regular expression, you can use
/::((?:[^:]|:(?!:))*)$/
. First, it matches a literal::
. Then, we use parentheses to put the desired thing in capturing group 1. The desired thing is one or more copies of a(?:...)
-bracketed string; this bracketing groups without capturing. We then look for either[^:]
, a non-colon character, or:(?!:)
, a colon followed by a non-colon. The(?!...)
is a negative lookahead, which matches only if the next token doesn't match the contained pattern. Since JavaScript doesn't support negative lookbehinds, I can't see a good way to avoid capturing the::
as well, but you can wrap this in a function:虽然
string
可能不是字符串名称的最佳选择?though perhaps
string
isn't the best choice of name for your string?