【发布时间】:2010-11-04 05:03:01
【问题描述】:
我正在尝试使用正则表达式替换字符串中的最后一个点。
假设我有以下字符串:
String string = "hello.world.how.are.you!";
我想用感叹号替换最后一个点,结果是:
"hello.world.how.are!you!"
我用String.replaceAll(String, String)的方法尝试了各种表达方式,没有任何运气。
【问题讨论】:
我正在尝试使用正则表达式替换字符串中的最后一个点。
假设我有以下字符串:
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("[.]$", "");
【讨论】: