LoginSignup
2
0

More than 1 year has passed since last update.

【Java】正規表現で最後にマッチした文字列のみを置換する方法

Last updated at Posted at 2022-04-15

正規表現で最初にマッチした文字列のみを置換する方法としてreplaceFirstメソッドが存在するが、最後にマッチした文字列のみを置換するreplaceLastメソッドはない。
探してみたところ、replaceFirstを応用して自作している人がいた為、使わせていただいた。

replace.java
public static void main(String[] args) throws Exception {
 
    String str = "hoge 0123 PIYO 4567 hoge 890 FUGA";
 
    // 小文字アルファベットの1回以上の繰り返しを""abc""に置換
    String result1 = replaceLast(str, "[a-z]+", "abc");
 
    System.out.println( result1 ); // hoge 0123 PIYO 4567 abc 890 FUGA
}
 
public static String replaceLast(String str, String regex, String replacement) {
    if(str == null || str.isEmpty()){
        return str;
    }
    
    return str.replaceFirst(regex+"(?!.*?"+regex+")", replacement);
}

否定先読みでregexを指定することで最後にマッチした文字列のみを置換するようにしているっぽい。
正規表現できる人すごい...

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0