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








Question

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

Answer

/*  w w w  . j  a v a  2  s.  c  om*/

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

public class Main {

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

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

      source = source.trim();

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

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

      } else {
          return source;
      }
  }

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

The code above generates the following result.