BigQuery - 匹配已知字符串后 8 位数字的正则表达式

BigQuery - Regex to match number of 8 digits after a known string

我需要提取已知字符串后的 8 位数字:

| MyString                     | Extract: | 
| ---------------------------- | -------- | 
| mypasswordis 12345678        | 12345678 | 
| # mypasswordis 12345678      | 12345678 | 
| foobar mypasswordis 12345678 | 12345678 |

我可以用正则表达式来做到这一点:

(?<=mypasswordis.*)[0-9]{8})

但是,当我想在 BigQuery 中使用 REGEXP_EXTRACT 命令执行此操作时,我收到错误消息 "Cannot parse regular expression: invalid perl operator: (?<"。

我搜索了 re2 library,发现其中似乎没有正向后视的等价物。

有什么方法可以使用其他方法来做到这一点吗?像

SELECT REGEXP_EXTRACT(MyString, r"(?<=mypasswordis.*)[0-9]{8}"))

这里需要一个捕获组来提取模式的一部分,参见REGEXP_EXTRACT docs you linked to:

If the regular expression contains a capturing group, the function returns the substring that is matched by that capturing group. If the expression does not contain a capturing group, the function returns the entire matching substring.

另外,.*模式开销太大,只需要匹配单词和数字之间的空格即可。

使用

SELECT REGEXP_EXTRACT(MyString, r"mypasswordis\s*([0-9]{8})"))

或者只是

SELECT REGEXP_EXTRACT(MyString, r"mypasswordis\s*([0-9]+)"))

参见re2 regex online test

尽量不要使用正则表达式,它很慢。以 substring 和 instr 为例:

SELECT SUBSTR(MyString, INSTR(MyString,'mypasswordis') + LENGTH('mypasswordis')+1)

否则 Wiktor Stribiżew 可能有正确答案。