Regex to find last token on a string
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
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 $
.
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.
function lastToken(str) {
var xs = str.split('::');
return xs.length > 1 ? xs.pop() : null;
}
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:
function lastTokenRegex(str) {
var m = str.match(/::((?:[^:]|:(?!:))*)$/);
return m && m[1];
}
var string2 = string.replace(/.*::/, "");
though perhaps string
isn't the best choice of name for your string?
精彩评论