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

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

假设我有以下字符串:

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("[.]$", "");