我正在尝试使用正则表达式替换字符串中的最后一个点。
假设我有以下字符串:
String string = "hello.world.how.are.you!";
我想将最后一个点替换为感叹号,使结果为:
"hello.world.how.are!you!"
我尝试使用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("[.]$", "");
^(.*)\\.(.*?)$
? - Emil Lundberg