Quantcast
Channel: プログラム の個人的なメモ
Viewing all articles
Browse latest Browse all 860

【Java】正規表現 [5] 不要文字除去 / 対象文字のみ抽出 ~ replaceFirst / replaceAll ~

$
0
0

はじめに

 * 例えば、「数字以外除外(数字のみ抽出)」など行いたい場合の方法。
  => 数字以外を空白文字 "" で置き換えればいい
  => 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


関連記事

正規表現 [1] 一致・不一致の判定 ~Matcher.matches() ~

http://blogs.yahoo.co.jp/dk521123/33605882.html

正規表現 [2] 複雑な文字列置き換え ~ replaceFirst / replaceAll ~

http://blogs.yahoo.co.jp/dk521123/34781790.html

正規表現 [3] 数字/文字の出現回数を数える ~Matcher.find() ~

http://blogs.yahoo.co.jp/dk521123/36448306.html

正規表現 [4] 文字列の抽出 ~Matcher.group() ~

http://blogs.yahoo.co.jp/dk521123/36604177.html

Viewing all articles
Browse latest Browse all 860

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>