Android で よくある正規表現を使えるやつ

そもそもは Linkify のWEBリンクがなんだかな, と思い.

device-2011-08-23-153643

使えそうなよくある正規表現がいくつか用意されていたのですな.

public static final Pattern WEB_URL = Pattern.compile(
    "((?:(http|https|Http|Https|rtsp|Rtsp):\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)"
  + "\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_"
  + "\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?"
  + "(?:" + DOMAIN_NAME + ")"
  + "(?:\\:\\d{1,5})?)"
  + "(\\/(?:(?:[" + GOOD_IRI_CHAR + "\\;\\/\\?\\:\\@\\&\\=\\#\\~"
  + "\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*)?"
  + "(?:\\b|$)");
public static final Pattern PHONE
  = Pattern.compile(                
      "(\\+[0-9]+[\\- \\.]*)?"      
    + "(\\([0-9]+\\)[\\- \\.]*)?"   
    + "([0-9][0-9\\- \\.]+[0-9])"); 
public static final Pattern EMAIL_ADDRESS
  = Pattern.compile(
    "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
    "\\@" +
    "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
    "(" +
        "\\." +
        "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
     ")+"
  );

platform_frameworks_base/Patterns.java

すぐにそのまま使おう.


if (Patterns.WEB_URL.matcher(text).find()) {
  // do something
}

「厳格なのか?」でフィルターをつける場合.

// A match filter that only accepts odd numbers.
MatchFilter oddFilter = new MatchFilter() {
    public final boolean acceptMatch(CharSequence s, int start, int end) {
        int n = Character.digit(s.charAt(end-1), 10);
        return (n & 1) == 1;
    }
};

// Match all digits in the pattern but restrict links to only odd
// numbers using the filter.
Pattern pattern = Pattern.compile("[0-9]+");
Linkify.addLinks(text, pattern, "http://...", oddFilter, null);

Android Text Links Using Linkify