All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.metamx.common.parsers.RegexParser Maven / Gradle / Ivy

There is a newer version: 1.3.8
Show newest version
/*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package com.metamx.common.parsers;

import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.metamx.common.collect.Utils;

import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 */
public class RegexParser implements Parser
{
  private final String pattern;
  private final Splitter listSplitter;
  private final Function valueFunction;
  private final Pattern compiled;

  private List fieldNames = null;

  public RegexParser(
      final String pattern,
      final Optional listDelimiter
  )
  {
    this.pattern = pattern;
    this.listSplitter = Splitter.onPattern(listDelimiter.isPresent()
                                           ? listDelimiter.get()
                                           : Parsers.DEFAULT_LIST_DELIMITER);
    this.valueFunction = new Function()
    {
      @Override
      public Object apply(String input)
      {
        final List retVal = Lists.newArrayList(
            Iterables.transform(
                listSplitter.split(input),
                ParserUtils.nullEmptyStringFunction
            )
        );
        if (retVal.size() == 1) {
          return retVal.get(0);
        } else {
          return retVal;
        }
      }
    };
    this.compiled = Pattern.compile(pattern);
  }

  public RegexParser(
      final String pattern,
      final Optional listDelimiter,
      final Iterable fieldNames
  )
  {
    this(pattern, listDelimiter);

    setFieldNames(fieldNames);
  }

  @Override
  public Map parse(String input)
  {
    try {
      final Matcher matcher = compiled.matcher(input);

      if (!matcher.matches()) {
        throw new ParseException("Incorrect Regex: %s . No match found.", pattern);
      }

      List values = Lists.newArrayList();
      for (int i = 1; i <= matcher.groupCount(); i++) {
        values.add(matcher.group(i));
      }

      if (fieldNames == null) {
        setFieldNames(ParserUtils.generateFieldNames(values.size()));
      }

      return Utils.zipMapPartial(fieldNames, Iterables.transform(values, valueFunction));
    }
    catch (Exception e) {
      throw new ParseException(e, "Unable to parse row [%s]", input);
    }
  }

  @Override
  public void setFieldNames(Iterable fieldNames)
  {
    ParserUtils.validateFields(fieldNames);
    this.fieldNames = Lists.newArrayList(fieldNames);
  }

  @Override

  public List getFieldNames()
  {
    return fieldNames;
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy