PageRenderTime 1718ms CodeModel.GetById 11ms app.highlight 5ms RepoModel.GetById 1ms app.codeStats 1699ms

/tags/release-0.0.0-rc0/hive/external/ql/src/java/org/apache/hadoop/hive/ql/udf/UDFRegExpExtract.java

#
Java | 65 lines | 35 code | 8 blank | 22 comment | 8 complexity | 8709db4bab408a46e355206ecf3db7c9 MD5 | raw file
 1/**
 2 * Licensed to the Apache Software Foundation (ASF) under one
 3 * or more contributor license agreements.  See the NOTICE file
 4 * distributed with this work for additional information
 5 * regarding copyright ownership.  The ASF licenses this file
 6 * to you under the Apache License, Version 2.0 (the
 7 * "License"); you may not use this file except in compliance
 8 * with the License.  You may obtain a copy of the License at
 9 *
10 *     http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19package org.apache.hadoop.hive.ql.udf;
20
21import java.util.regex.MatchResult;
22import java.util.regex.Matcher;
23import java.util.regex.Pattern;
24
25import org.apache.hadoop.hive.ql.exec.Description;
26import org.apache.hadoop.hive.ql.exec.UDF;
27
28/**
29 * UDF to extract a specific group identified by a java regex. Note that if a
30 * regexp has a backslash ('\'), then need to specify '\\' For example,
31 * regexp_extract('100-200', '(\\d+)-(\\d+)', 1) will return '100'
32 */
33@Description(name = "regexp_extract",
34    value = "_FUNC_(str, regexp[, idx]) - extracts a group that matches regexp",
35    extended = "Example:\n"
36    + "  > SELECT _FUNC_('100-200', '(\\d+)-(\\d+)', 1) FROM src LIMIT 1;\n"
37    + "  '100'")
38public class UDFRegExpExtract extends UDF {
39  private String lastRegex = null;
40  private Pattern p = null;
41
42  public UDFRegExpExtract() {
43  }
44
45  public String evaluate(String s, String regex, Integer extractIndex) {
46    if (s == null || regex == null) {
47      return null;
48    }
49    if (!regex.equals(lastRegex) || p == null) {
50      lastRegex = regex;
51      p = Pattern.compile(regex);
52    }
53    Matcher m = p.matcher(s);
54    if (m.find()) {
55      MatchResult mr = m.toMatchResult();
56      return mr.group(extractIndex);
57    }
58    return "";
59  }
60
61  public String evaluate(String s, String regex) {
62    return this.evaluate(s, regex, 1);
63  }
64
65}