简体   繁体   English

正则表达式仅匹配最后一个破折号后的数字

[英]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. 我也尝试过此方法,它可以解决连字符问题,但是仅在连字符后匹配2个或多个数字。 For example it won't match "1" in "one-1" but it'll match "12" in "one-12". 例如,它在“ one-1”中不匹配“ 1”,但在“ one-12”中匹配“ 12”。

[^-]\d+$

I would like to note that I am using the javascript string replace() method. 我想指出的是,我正在使用javascript字符串replace()方法。

In PCRE languages that support lookbehinds, you can simply do a positive lookbehind: 在支持后向支持的PCRE语言中,您可以简单地进行后向支持:

(?<=-)\d+$

Example: https://regex101.com/r/dW6wP3/1 示例: 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: 但是,由于您使用的是Javascript(不支持lookbehinds),因此可以使用捕获组来捕获所需的内容:

(?:-)(\d+)$

Example: https://regex101.com/r/zP1cO6/1 范例: 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+$/, ''));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM