hive中正则表达式的使用。
1、regexp
regexp的用法与like相似,但是在进行复杂匹配或者同一字段匹配不同字符串且有先后顺序时,regexp使用较为方便。
语法: A REGEXP B
2.regexp_extract
语法:regexp_extract(string subject, string pattern, int index)
使用pattern从给定字符串中提取字符串。如: regexp_extract('foothebar', 'foo(.*?)(bar)', 2) 返回'bar' 有时需要使用预定义的字符类:使用'\s' 做为第二个参数将匹配s,'s'匹配空格等。参数index是Java正则匹配器方法group()方法中的索引
hive> select regexp_extract('foothebar', 'foo(.*?)(bar)', 1) fromiteblog;
the
hive> select regexp_extract('foothebar', 'foo(.*?)(bar)', 2) fromiteblog;
bar
hive> select regexp_extract('foothebar', 'foo(.*?)(bar)', 0) fromiteblog;
foothebar
*注意,在有些情况下要使用转义字符,下面的等号要用双竖线转义,这是java正则表达式的规则
select data_field,
regexp_extract(data_field,'.*?bgStart\\=([^&]+)',1) as aaa,
regexp_extract(data_field,'.*?contentLoaded_headStart\\=([^&]+)',1) as bbb,
regexp_extract(data_field,'.*?AppLoad2Req\\=([^&]+)',1) as ccc
from pt_nginx_loginlog_st
where pt = '2012-03-26'limit 2;
3.regexp_replace
语法:regexp_replace(string INITIAL_STRING, string PATTERN, string REPLACEMENT)
使用REPLACEMENT替换字符串INITIAL_STRING中匹配PATTERN的子串,例如: regexp_replace("foobar", "oo|ar", "") 返回'fb'
select regexp_replace('fooobar', 'oo|ar', '') from tb_table;
返回值:fob
4.split
语法:split(string str, string pat)
用pat分割字符串str,pat为正则表达式
select split('abtcdtef','t') from tb_table;
返回值:["ab","cd","ef"]
5.like
语法1: A LIKE B
语法2: LIKE(A, B)
返回类型: boolean或null
描述: 如果字符串A符合表达式B的正则语法,则为TRUE;否则为FALSE。B中字符"_"表示任意单个字符,而字符"%"表示任意数量的字符。
select 'football' like '%ba';
返回值:false
select 'football' like '%ba%';
返回值:true
select 'football' like '__otba%';
返回值:true
select like('football', '__otba%');
返回值:true