java 如何使用正则表达式替换字符串中的最后一个点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4094024/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 04:44:35  来源:igfitidea点击:

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

javaregexstring

提问by digiarnie

I'm trying to replace the last dot in a String using a regular expression.

我正在尝试使用正则表达式替换字符串中的最后一个点。

Let's say I have the following String:

假设我有以下字符串:

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

I want to replace the last dot with an exclamation mark such that the result is:

我想用感叹号替换最后一个点,结果是:

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

I have tried various expressions using the method String.replaceAll(String, String)without any luck.

我尝试了使用该方法的各种表达式,String.replaceAll(String, String)但没有任何运气。

回答by codaddict

One way would be:

一种方法是:

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

Alternatively you can use negative lookahead as:

或者,您可以使用负前瞻作为:

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

Regex in Action

正则表达式在行动

回答by paxdiablo

Although you can use a regex, it's sometimes best to step back and just do it the old-fashioned way. I've always been of the belief that, if you can't think of a regex to do it in about two minutes, it's probably not suited to a regex solution.

虽然您可以使用正则表达式,但有时最好退后一步,按照老式的方式来做。我一直相信,如果你想不出一个正则表达式在大约两分钟内完成它,它可能不适合正则表达式解决方案。

No doubt get some wonderful regex answers here. Some of them may even be readable :-)

毫无疑问,在这里可以得到一些精彩的正则表达式答案。其中一些甚至可能是可读的:-)

You can use lastIndexOfto get the last occurrence and substringto build a new string: This complete program shows how:

您可以使用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 ."));
    }
}

The output is:

输出是:

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

回答by John La Rooy

The regex you need is \\.(?=[^.]*$). the ?=is a lookahead assertion

您需要的正则表达式是\\.(?=[^.]*$). 这?=是一个前瞻断言

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

回答by panticz

Try this:

试试这个:

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