[英]How to replace last dot in a string using a regular expression?
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)
方法的各种表达式String.replaceAll(String, String)
没有任何运气。
One way would be: 一种方法是:
string = string.replaceAll("^(.*)\\.(.*)$","$1!$2");
Alternatively you can use negative lookahead as: 或者,您可以使用负前瞻方式:
string = string.replaceAll("\\.(?!.*\\.)","!");
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 lastIndexOf
to get the last occurrence and substring
to 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 !
The regex you need is \\\\.(?=[^.]*$)
. 您需要的正则表达式是\\\\.(?=[^.]*$)
。 the ?=
is a lookahead assertion ?=
是一个前瞻性断言
"hello.world.how.are.you!".replace("\\.(?=[^.]*$)", "!")
尝试这个:
string = string.replaceAll("[.]$", "");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.