天天看点

hive函数:regexp_extract 正则表达式函数

目标:取出["4873748","666"]数组中的数字。

方式:正则表达式选择。

regexp_extract 函数,第一个参数为要解析的数组或字符串等,第二个参数为正则表达式,第三个索引。

这里,参数一:["4873748","666"]

参数二:([0-9]+) 正则表达式,意为筛选数字,这里的‘+’指的是,多次重复

参数三:0 (0表示把整个符合正则表达式对应的结果全部返回)

        1 (1表示返回正则表达式中第一个() 对应的结果 以此类推)

select regexp_extract('["4873748","666"]','([0-9]+)',0);

+----------+--+

|   _c0    |

+----------+--+

| 4873748  |

+----------+--+

解析:按理说0应该返回全部结果值,可是为什么只有’4873748’一个呢?是因为参数二的正则表达式,()代表子表达式。现参数二内只有一个子表达式,所以能够匹配上的也只有第一组数字,因此不论参数三填写索引0还是1,值都是一样的。而索引填写大于1的值时,系统就会出现报错。

select regexp_extract('["4873748","666"]','([0-9]+)',1);

+----------+--+

|   _c0    |

+----------+--+

| 4873748  |

+----------+--+

select regexp_extract('["4873748","666"]','([0-9]+)',2);

Error: Error while compiling statement: FAILED: SemanticException [Error 10014]: Line 1:7 Wrong arguments '2': org.apache.hadoop.hive.ql.metadata.HiveException: Unable to execute method public java.lang.String org.apache.hadoop.hive.ql.udf.UDFRegExpExtract.evaluate(java.lang.String,java.lang.String,java.lang.Integer)  on object [email protected] of class org.apache.hadoop.hive.ql.udf.UDFRegExpExtract with arguments {["4873748","666"]:java.lang.String, ([0-9]+):java.lang.String, 2:java.lang.Integer} of size 3 (state=42000,code=10014)

为了更容易理解,在上文栗子的基础上,对参数二进行了补充,添加了两个子表达式,因此其索引增加至了3。

这里索引0,将符合正则表达式的所有结果值返回。其实,也可以把子表达式看做是数组,只不过不同的是,这里0返回全部,1是位置1,2是位置2。

select regexp_extract('["4873748","666"]','([0-9]+)(.*?)([0-9]+)',0);

+----------------+--+

|      _c0       |

+----------------+--+

| 4873748","666  |

+----------------+--+

select regexp_extract('["4873748","666"]','([0-9]+)(.*?)([0-9]+)',1);

+----------+--+

|   _c0    |

+----------+--+

| 4873748  |

+----------+--+

select regexp_extract('["4873748","666"]','([0-9]+)(.*?)([0-9]+)',2);

+------+--+

| _c0  |

+------+--+

| ","  |

+------+--+

select regexp_extract('["4873748","666"]','([0-9]+)(.*?)([0-9]+)',3);

+------+--+

| _c0  |

+------+--+

| 666  |

+------+--+

继续阅读