【问题标题】:Using regex to extract product name from URL with Google BigQuery使用正则表达式从带有 Google BigQuery 的 URL 中提取产品名称
【发布时间】:2021-05-21 01:48:15
【问题描述】:

我正在尝试使用 Google BigQuery 中的正则表达式从以下 URL 中提取产品名称:

https://www.example.com/en/uk/product/clothing/trousers-leggings/cool-grey-joggers-9800977

产品名称应为:cool-grey-joggers

https://www.example.com/en/uk/product/hot-denim-dress-7842666

产品名称应为:hot-denim-dress

我尝试了以下正则表达式:

'/product/(.+)-[0-9]+$'

但这似乎是贪心匹配,会返回:

clothing/trousers-leggings/cool-grey-joggers

hot-denim-dress

我已经尝试了上述方法的多种变体,但要么不匹配,要么捕获太多。

如何修改以便它只捕获产品名称而不捕获父子文件夹?

【问题讨论】:

    标签: regex google-bigquery


    【解决方案1】:

    试试这个:

    SELECT REGEXP_EXTRACT('https://www.example.com/en/uk/product/clothing/trousers-leggings/cool-grey-joggers-9800977', r'([^/]+)-[0-9]+$')
    UNION ALL
    SELECT REGEXP_EXTRACT('https://www.example.com/en/uk/product/hot-denim-dress-7842666', r'([^/]+)-[0-9]+$')
    

    【讨论】:

      【解决方案2】:

      如果/product/ 必须是路径的一部分:

      /product/(?:[^/]+/)*([^/]+)-[0-9]+$
      

      模式匹配:

      • /product/ 字面匹配
      • (?:[^/]+/)* 可选择重复以/ 结尾的匹配部分
      • ([^/]+) 捕获 group 1,匹配除 / 之外的任何字符的 1+ 次出现
      • -[0-9]+$ 匹配 - 和 1+ 位直到字符串结尾

      Regex demo

      【讨论】:

        猜你喜欢
        • 2017-04-07
        • 2017-04-08
        • 1970-01-01
        • 2019-01-16
        • 1970-01-01
        • 2021-02-09
        • 1970-01-01
        • 2018-07-20
        • 1970-01-01
        相关资源
        最近更新 更多