我正在尝试使用正则表达式替换String中的最后一个点.
假设我有以下字符串:
String string = "hello.world.how.are.you!";
Run Code Online (Sandbox Code Playgroud)
我想用感叹号替换最后一个点,结果是:
"hello.world.how.are!you!"
Run Code Online (Sandbox Code Playgroud)
我已经尝试了使用该方法的各种表达,String.replaceAll(String, String)没有任何运气.
cod*_*ict 13
一种方法是:
string = string.replaceAll("^(.*)\\.(.*)$","$1!$2");
Run Code Online (Sandbox Code Playgroud)
或者,你可以使用负向前瞻:
string = string.replaceAll("\\.(?!.*\\.)","!");
Run Code Online (Sandbox Code Playgroud)
虽然你可以使用正则表达式,但有时最好退后一步,按照老式的方式来做.我一直相信,如果你想不到一个正则表达式在大约两分钟内完成它,它可能不适合正则表达式解决方案.
毫无疑问,这里有一些很棒的正则表达式答案.其中一些甚至可能是可读的:-)
您可以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 ."));
}
}
Run Code Online (Sandbox Code Playgroud)
输出是:
hello.world.how.are!you!
no dots in here
! first
last !
Run Code Online (Sandbox Code Playgroud)
你需要的正则表达式是\\.(?=[^.]*$).这?=是一个先行的断言
"hello.world.how.are.you!".replace("\\.(?=[^.]*$)", "!")
Run Code Online (Sandbox Code Playgroud)