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