Pig 0.11 里 REGEX_EXTRACT() 中正則表達式的正確用法

来源:互联网 发布:iphone照片导出到mac 编辑:程序博客网 时间:2024/05/17 01:14

本人之前從未接觸過正則表達式,了解到pig 中match 和 REGEX_EXTRACT 都是基於 java 的正則表達式,於是在java 官網 http://docs.oracle.com/javase/tutorial/essential/regex/index.html 惡補了一下。


用官網提供的程序(ps: 那程序只能在cmd編譯后跑,eclipse上跑不起)拼了一個式子來截取頂級域名:

\.[a-z0-9A-Z]+\.(com|hk|cc|org|tv)


之後直接放在REGEX_EXTRACT() 中,問題們來了:

1.因為pig中本身\已有特殊含義,所以\.转义在pig中应为\\.

2.《Programming Pig》和 stackoverflow上面的家伙坑爹啊,书上附录说REGEX_EXTRACT()第三个参数是从0开始。

     Totally wrong!第三个参数是从1开始算的!尼玛就是坑我这种小学生,请看pig官网:http://pig.apache.org/docs/r0.11.1/func.html#regex-extract

REGEX_EXTRACT

Performs regular expression matching and extracts the matched group defined by an index parameter.

Syntax

REGEX_EXTRACT (string, regex, index)

Terms

string

The string in which to perform the match.

regex

The regular expression.

index

The index of the matched group to return.

Usage

Use the REGEX_EXTRACT function to perform regular expression matching and to extract the matched group defined by the index parameter (where the index is a 1-based parameter.) The function uses Java regular expression form.

The function returns a string that corresponds to the matched group in the position specified by the index. If there is no matched expression at that position, NULL is returned.

Example

This example will return the string '192.168.1.5'.

REGEX_EXTRACT('192.168.1.5:8020', '(.*):(.*)', 1);



为神马这么奇怪上面example会是192.168.1.5 而不是192.168.1.5:8020呢?

答案就是REGEX_EXTRACT 的里第3个参数‘1’表示截取正则表达式里'(.*):(.*)' 的第一个括号里的(.*)作为结构返回!!!

因此,要将上面的表达式改为  

([a-z0-9A-Z]+\\.(com|hk|cc|org|tv)).

這樣參數1就代表整個表達式,結果類似baidu.com之類

2就代表(com|hk|cc|org|tv))

詳情可參考java官網:http://docs.oracle.com/javase/tutorial/essential/regex/groups.html


原创粉丝点击