はじめに
* 例えば、「数字以外除外(数字のみ抽出)」など行いたい場合の方法。 => 数字以外を空白文字 "" で置き換えればいい => replaceAll("【正規表現】", "") でいい => 以下の例2のように、場合によっては、replaceFirst("【正規表現】", "") も使える * replaceFirst / replaceAll については、以下の関連記事を参照のことhttp://blogs.yahoo.co.jp/dk521123/34781790.html
サンプル
■ 例1 : カタカナ以外除外(カタカナのみ抽出)
public class Main { public static void main(String[] args) { String input = "ア=イ\\ウ|エ&オ%4カ;キ#ク*ケ;コ++"; String result = input.replaceAll("[^\\u30A0-\\u30FF]", ""); System.out.println("Result : " + result); } }出力結果
Result : アイウエオカキクケコ
■ 例2 : 語尾の削除
textValue.substring(0, textValue.length()-1) だと無条件で語尾を削除してしまうhttp://npnl.hatenablog.jp/entry/20090917/1253160217
を参考にしているが、そのままだとコンパイルエラー。「\\$」だとうまくいかない
import java.text.MessageFormat; public class Replacer { private static final String FORMAT_FOR_REMOVE_LAST = "{0}$"; public static void main(String[] args) { System.out.println(removeLast("サーバー", "ー")); System.out.println(removeLast("サーバ", "ー")); System.out.println(removeLast("メモリー", "ー")); System.out.println(removeLast("メモリ", "ー")); System.out.println(removeLast("aaa,bbb,", ",")); System.out.println(removeLast("aaa,bbb", ",")); } public static String removeLast(String textValue, String regex) { if (textValue == null) { return null; } return textValue.replaceFirst(MessageFormat.format(FORMAT_FOR_REMOVE_LAST, regex), ""); } }出力結果
サーバ サーバ メモリ メモリ aaa,bbb aaa,bbb
参考文献
https://oshiete.goo.ne.jp/qa/1029431.html文字種ごとの正規表現
http://d.hatena.ne.jp/dirablue/20090506/1241607961