正则表达式:匹配之后的内容,但不包括匹配内容本身

4

我将尝试对以下字符串进行正则表达式匹配:

https://www.amazon.com/Tapps-Top-Apps-and-Games/dp/B00VU2BZRO/ref=sr_1_3?ie=UTF8&qid=1527813329&sr=8-3&keywords=poop

我只想要 B00VU2BZRO

这个子字符串总是由dp/前缀的10个字母数字组成。

到目前为止,我有以下正则表达式:

[d][p][\/][0-9B][0-9A-Z]{9}

这个匹配的是 dp/B00VU2BZRO

我只想匹配B00VU2BZRO,而不包含dp/

我该如何使用正则表达式实现?


添加语言标签并展示如何应用它。捕获组和正向后顾断言都可以使用。 - Mad Physicist
为了提高搜索性能,以下是从亚马逊URL中提取ASIN的方法。 - Raleigh L.
2个回答

4

以下是一个正则表达式选项,它可以精确匹配您想要的内容:

(?<=dp\/)(.*)(?=\/)

示例

请注意,此解决方案不会对dp/后出现的路径片段长度做任何假设。如果您想匹配一定数量的字符,请将(.*)替换为(.{10}),例如。


1

根据您的语言/应用程序方法,您有几个选择。

  1. Positive look behind. This will make your regex more complicated, but will make it match what you want exactly:

    (<=dp/)[0-9A-Z]{10}
    

    The construct (<=...) is called a positive look behind. It will not consume any of the string, but will only allow the match to happen if the pattern between the parens is matched.

  2. Capture group. This will make the regex itself slightly simpler, but will add a step to the extraction process:

    dp/([0-9A-Z]{10})
    

    Anything between plain parens is a capture group. The entire pattern will be matched, including dp/, but most languages will give you a way of extracting the portion you are interested in.

根据您的语言,您可能需要转义正斜杠 (/)。

顺便提一下,您永远不需要为单个字符创建字符类:[d][p][\/] 同样可以写成 dp\/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接