Rick
Rick

Reputation: 711

Regular expression to match only numbers after the last dash

I'm really close but just can't quite figure out one last thing. I'm trying to get it to match only the digits without the hyphen.

For example the below shows the desired match in parenthesis:

one (no match)
one-1 (1)
one-two (no match)
one-two-2 (2)
one-two-23 (23)
one-two-23456 (23456)
one-two-three (no match)
one-two-three-1 (1)
one-two-three-23 (23)
one-0-two-three-2343 (2343)
one-0-44-2343233 (2343233)
one-0-two-three-234and324 (no match)

I've tried a couple patterns so far and here's the results.

This is close but the matches include the hyphen.

-\d+$

I've tried this as well which fixes the hyphen issue but then only matches 2 or more digits after hyphens. For example it won't match "1" in "one-1" but it'll match "12" in "one-12".

[^-]\d+$

I would like to note that I am using the javascript string replace() method.

Upvotes: 1

Views: 1242

Answers (1)

brandonscript
brandonscript

Reputation: 73034

In PCRE languages that support lookbehinds, you can simply do a positive lookbehind:

(?<=-)\d+$

Example: https://regex101.com/r/dW6wP3/1

But since you're using Javascript (which doesn't support lookbehinds), you could use capture groups to grab what you need instead:

(?:-)(\d+)$

Example: https://regex101.com/r/zP1cO6/1

You'd use it like this:

var text = "one-two-23";
console.log(text.match(/(?:-)(\d+)$/)[1]); // 23

Edit: Since you're trying to replace, that changes things. You'll need to do:

var text = "one-two-23";
if (/-\d+$/.test(text)) {
    console.log(text.replace(/\d+$/, ''));
}

Upvotes: 2

Related Questions