如何使用正则表达式替换字符串中的最后一个点? [英] How to replace last dot in a string using a regular expression?
本文介绍了如何使用正则表达式替换字符串中的最后一个点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用正则表达式替换String中的最后一个点。
I'm trying to replace the last dot in a String using a regular expression.
假设我有以下字符串:
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!"
我已尝试使用方法 String.replaceAll(String,String)的各种表达式)
没有任何运气。
I have tried various expressions using the method String.replaceAll(String, String)
without any luck.
推荐答案
一种方法是:
string = string.replaceAll("^(.*)\\.(.*)$","$1!$2");
或者你可以使用负向前瞻:
Alternatively you can use negative lookahead as:
string = string.replaceAll("\\.(?!.*\\.)","!");
这篇关于如何使用正则表达式替换字符串中的最后一个点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文