001/***************************************************************************
002 * Copyright 2010 Global Biodiversity Information Facility Secretariat
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
005 * use this file except in compliance with the License. You may obtain a copy of
006 * the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
012 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
013 * License for the specific language governing permissions and limitations under
014 * the License.
015 ***************************************************************************/
016
017package org.gbif.utils.text;
018
019import java.util.regex.Matcher;
020import java.util.regex.Pattern;
021
022import org.apache.commons.lang3.StringUtils;
023
024public class EmailUtils {
025
026  public static class EmailWithName {
027
028    public String email;
029    public String name;
030  }
031
032  private static final Pattern EMAIL_PATTERN =
033    Pattern.compile("(?:(.+)(?: +| *<))?([^@ ]+(?:@| at )[^@ ]+\\.[a-zA-Z0-9_-]{2,4})(?: *>)?");
034
035  public static EmailWithName parseEmail(String x) {
036    if (StringUtils.isBlank(x)) {
037      return null;
038    }
039    EmailWithName n = new EmailWithName();
040    Matcher m = EMAIL_PATTERN.matcher(x);
041    if (m.find()) {
042      //      int all = m.groupCount();
043      //      int idx = 0;
044      //      while (idx<=all){
045      //        System.out.println(m.group(idx));
046      //        idx++;
047      //      }
048      n.name = StringUtils.trimToNull(m.group(1));
049      n.email = StringUtils.trimToNull(m.group(2));
050    } else {
051      n.name = StringUtils.trimToNull(x);
052    }
053    return n;
054  }
055
056  private EmailUtils() {
057    throw new UnsupportedOperationException("Can't initialize class");
058  }
059}