首页 > 解决方案 > Biq 查询 regex_replace 错误 (\? vs \\?)

问题描述

我在理解这个正则表达式有什么问题时遇到了问题:\?.*

 select REGEXP_REPLACE(longstringcolumn, '\?.*', '') as newstring from tablename

我的示例字符串 aka 'longstring' 有 '?' 字符,我正在尝试匹配尾随'?(包括“?”本身)。

我已经在在线工具中检查了我的正则表达式,我的正则表达式似乎正在工作。

编辑

感谢大家这么快,这是一个示例字符串(它是一个 url):

http://example.com/one/two/three?lang=en®ion=CN

我试图在“?”之后剥离所有内容。所以这部分:

?lang=en®ion=CN

这是我返回的错误:无法解析正则表达式“?”:重复运算符没有参数:?

我真的倾向于这是一个简单的转义字符问题,但我无法以某种方式弄清楚。

标签: sqlregexgoogle-bigquery

解决方案


#standardSQL
SELECT REGEXP_REPLACE(longstringcolumn, '\\?.*', '') AS newstring 
FROM tablename  

或者

#standardSQL
SELECT REGEXP_REPLACE(longstringcolumn, r'\?.*', '') AS newstring 
FROM tablename

下面的例子

#standardSQL
WITH tablename AS (
  SELECT 'is this a question?abc ' AS longstringcolumn UNION ALL
  SELECT 'this is not a question' union all
  SELECT'http://example.com/one/two/three?lang=en&region=CN'
)
SELECT REGEXP_REPLACE(longstringcolumn, r'\?.*', '') AS newstring 
FROM tablename  

结果为(在哪里?和所有尾随字符都被删除)

Row newstring    
1   is this a question   
2   this is not a question   

希望这表明您的原始查询有什么问题


推荐阅读