001 /** 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018 019 package org.apache.hadoop.mapreduce.lib.map; 020 021 import java.io.IOException; 022 import java.util.regex.Matcher; 023 import java.util.regex.Pattern; 024 025 import org.apache.hadoop.classification.InterfaceAudience; 026 import org.apache.hadoop.classification.InterfaceStability; 027 import org.apache.hadoop.conf.Configuration; 028 import org.apache.hadoop.io.LongWritable; 029 import org.apache.hadoop.io.Text; 030 import org.apache.hadoop.mapreduce.Mapper; 031 032 033 /** A {@link Mapper} that extracts text matching a regular expression. */ 034 @InterfaceAudience.Public 035 @InterfaceStability.Stable 036 public class RegexMapper<K> extends Mapper<K, Text, Text, LongWritable> { 037 038 public static String PATTERN = "mapreduce.mapper.regex"; 039 public static String GROUP = "mapreduce.mapper.regexmapper..group"; 040 private Pattern pattern; 041 private int group; 042 043 public void setup(Context context) { 044 Configuration conf = context.getConfiguration(); 045 pattern = Pattern.compile(conf.get(PATTERN)); 046 group = conf.getInt(GROUP, 0); 047 } 048 049 public void map(K key, Text value, 050 Context context) 051 throws IOException, InterruptedException { 052 String text = value.toString(); 053 Matcher matcher = pattern.matcher(text); 054 while (matcher.find()) { 055 context.write(new Text(matcher.group(group)), new LongWritable(1)); 056 } 057 } 058 }