hive提取字符串中域名的sql方法
<h1 id="hive提取字符串中域名的sql方法">hive提取字符串中域名的sql方法</h1><h2 id="需求如下">需求如下:</h2>
<p>想取如下字段里的访问的域名:</p>
<pre><code>"GET http://suo.im/4xhnBL HTTP/1.1"
"CONNECT sapi.ads.544.com:443 HTTP/1.1"
"GET http://100.110.1.52:8080/job/1/buildWithParameters?token=TOKEN&buildParams=%7B%22lintDir%22:%20%22 HTTP/1.1"
GET http://txmov2.a.yxis.com/u/BMjAxODEwjUzNDdfM18z_B36199d79e3.mp4?tag=1-1598-unknown4849&di=d4402759&bp=10000 HTTP/1.1
</code></pre>
<p>一开始思考的时候直接正则匹配http,但发现匹配不到如下字符串的域名:</p>
<p>正则参考:https://blog.csdn.net/yong472727322/article/details/73321935</p>
<pre><code>(http|https)*://(www.)?(\w+(\.)?)+
</code></pre>
<pre><code>"CONNECT sapi.ads.oppomobile.com:443 HTTP/1.1"
</code></pre>
<p><img src="https://blog-1254419664.cos.ap-chengdu.myqcloud.com/backup/20210413213833.png" alt="" loading="lazy"></p>
<p>发现hive有个函数regexp_extract很好:</p>
<h2 id="正则表达式解析函数regexp_extract"><strong>正则表达式解析函数:regexp_extract</strong></h2>
<p>语法: regexp_extract(string subject, string pattern, int index)</p>
<p>返回值: string</p>
<p>说明:将字符串subject按照pattern正则表达式的规则拆分,返回index指定的字符。</p>
<p>第三个参数:</p>
<p>0 是显示与之匹配的整个字符串</p>
<p>1 是显示第一个括号里面的</p>
<p>2 是显示第二个括号里面的字段</p>
<pre><code class="language-text">hive> select regexp_extract('foothebar', 'foo(.*?)(bar)', 1) from dual;
the
hive> select regexp_extract('foothebar', 'foo(.*?)(bar)', 2) from dual;
bar
hive> select regexp_extract('foothebar', 'foo(.*?)(bar)', 0) from dual;
foothebar
hive> select regexp_extract('中国abc123!','[\\u4e00-\\u9fa5]+',0) from dual; //实用:只匹配中文
hive> select regexp_replace('中国abc123','[\\u4e00-\\u9fa5]+','') from dual; //实用:去掉中文
</code></pre>
<p>注意,在有些情况下要使用转义字符,等号要用双竖线转义,这是java正则表达式的规则。</p>
<p>参考:</p>
<p>HIVE字符串处理技巧【总结】:https://zhuanlan.zhihu.com/p/82601425</p>
<h2 id="hive-sql-结果">hive sql 结果:</h2>
<pre><code> regexp_extract(request, '\\w+ ((http?)?(://))?([^/\\s]*)(/?.*) HTTP/.*', 4) as domain,
regexp_extract(request, '"(.*?)( )', 1) as method,
regexp_extract(request, '(HTTP/.*)(")', 1) as protocol,
</code></pre>
<h2 id="坑">坑:</h2>
<h3 id="hive-parse_url-函数的使用">hive parse_url 函数的使用</h3>
<p>hive parse_url 只能解析标准的url</p>
<p>https://blog.csdn.net/oracle8090/article/details/79637982</p>
<p>https://blog.csdn.net/weixin_30861459/article/details/96178140</p><br><br>
来源:https://www.cnblogs.com/Mang0/p/14655528.html
頁:
[1]