如何正则表达式仅提取第一个逗号或特定关键字之后的数字?

How to regex extract only numbers up to the first comma or after a specific keyword?

我在尝试从以下类型的字符串中 regex extract 'positions' 时遇到问题:

6 red players position 5, button 2
earn  pos3, up to ,000
earn  pos 2, up to 0
table button 4, before Jan 21

我想获取'pos'或'position'之后的数字,如果没有这样的关键字,则获取第一个逗号之前的最后一个数字。位置值可以是 1 到 100 之间的数字。因此,前面每一行的 'position' 将是:

Input text Desired match (position)
6 red players position 5, button 2 5
earn pos3, up to ,000 3
earn pos 2, up to 0 2
table button 4, before Jan 21 4

我有一个大数据集(在 BigQuery 中),基本上填充了这 4 种类型的字符串。

我已经搜索过此类问题,但找不到解决方案或起点。

我觉得有一种方法可以将这两者结合起来,但我还不知道如何实现。

因此,在我尝试了两件事之后,我有两个问题:

  1. 仅使用正则表达式是否可行?如果是,怎么做?
  2. 在 SQL 中我需要做什么才能让我的生活更轻松地获得这些价值?

我很感激help/guidance。非常感谢!

使用向前看逗号,向后看要求前一个字符是 space 或字母以防止匹配“$1,000”中的“1”:

(?<=[ a-z])(\d+)(?=,)

live demo

你可以使用

^(?:[^,]*[^0-9,])?(\d+),

参见RE2 regex demo详情:

  • ^ - 字符串开头
  • (?:[^,]*[^0-9,])? - 一个可选的序列:
    • [^,]* - 除逗号
    • 以外的零个或多个字符
    • [^0-9,] - 除了数字和逗号之外的字符
  • (\d+) - 第 1 组:一个或多个数字
  • , - 逗号