Java Data Type How to - Get the first word (pure alphabet word) from the String








Question

We would like to know how to get the first word (pure alphabet word) from the String.

Answer

import java.util.regex.Matcher;
import java.util.regex.Pattern;
//ww w .  j  a  v a2  s  .  co  m
public class Main {

  public static void main(String[] args) {
    System.out.println(getFirstWord("this is a test"));
  }

  /**
   * Get the first word (pure alphabet word) from the String
   * 
   * @param source
   *          the string where the first word is to be extracted
   * @return the extracted first word or null if there is no first word
   */
  public static String getFirstWord(String source) {
    if (source == null) {
      return null;
    }

    source = source.trim();

    if (source.isEmpty()) {
      return null;
    }

    if (containsSpace(source)) {

      final int FIRST_WORD_GROUP = 1;
      String firstWordRegex = "^[^A-z]*([A-z]+)";
      Pattern pattern = Pattern.compile(firstWordRegex);
      Matcher matcher = pattern.matcher(source);
      if (matcher.find()) {
        return matcher.group(FIRST_WORD_GROUP);
      } else {
        return null;
      }
    } else {
      return source;
    }
  }

  private static boolean containsSpace(String source) {
    return source.contains(" ");
  }
}

The code above generates the following result.