簡體   English   中英

如何使用正則表達式替換字符串中的最后一個點?

[英]How to replace last dot in a string using a regular expression?

我正在嘗試使用正則表達式替換字符串中的最后一個點。

假設我有以下字符串:

String string = "hello.world.how.are.you!";

我想用感嘆號替換最后一個點,使結果為:

"hello.world.how.are!you!"

我已經嘗試過使用String.replaceAll(String, String)方法的各種表達式String.replaceAll(String, String)沒有任何運氣。

一種方法是:

string = string.replaceAll("^(.*)\\.(.*)$","$1!$2");

或者,您可以使用負前瞻方式:

string = string.replaceAll("\\.(?!.*\\.)","!");

正則表達式在行動

盡管可以使用正則表達式,但有時最好退后一步,以老式的方式進行。 我一直堅信,如果您不能在大約兩分鍾內想到一個正則表達式,那可能不適合正則表達式解決方案。

毫無疑問,這里有一些很棒的正則表達式答案。 其中一些甚至是可讀的:-)

您可以使用lastIndexOf來獲取最后一次出現的信息,並可以使用substring來構建新的字符串:該完整程序演示了如何:

public class testprog {
    public static String morph (String s) {
        int pos = s.lastIndexOf(".");
        if (pos >= 0)
            return s.substring(0,pos) + "!" + s.substring(pos+1);
        return s;
    }
    public static void main(String args[]) {
        System.out.println (morph("hello.world.how.are.you!"));
        System.out.println (morph("no dots in here"));
        System.out.println (morph(". first"));
        System.out.println (morph("last ."));
    }
}

輸出為:

hello.world.how.are!you!
no dots in here
! first
last !

您需要的正則表達式是\\\\.(?=[^.]*$) ?=是一個前瞻性斷言

"hello.world.how.are.you!".replace("\\.(?=[^.]*$)", "!")

嘗試這個:

string = string.replaceAll("[.]$", "");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM