Java 替换特殊字符及其最右边的字符串

Java 替换特殊字符及其最右边的字符串,java,string,Java,String,可能重复: 我有以下字符串: "Hello $employee.$currency and $bankbalance" 我的任务是用另一个字符串替换$和以下字符串 我将在运行时获得更多类似的字符串,并且必须扫描并识别以$开头的任何字符串,并用相应的字符串替换它们 在运行时,所有以$开头的字符串都应替换为单个字符串我建议使用regex“\$[^.\n\0$]+” 查找模式的第一个和最后一个索引 Pattern pattern = Pattern.compile("\$[^\. \\n$]+"

可能重复:

我有以下字符串:

 "Hello $employee.$currency and $bankbalance"
我的任务是用另一个字符串替换
$
和以下字符串

我将在运行时获得更多类似的字符串,并且必须扫描并识别以
$
开头的任何字符串,并用相应的字符串替换它们

在运行时,所有以$开头的字符串都应替换为单个字符串

我建议使用regex“\$[^.\n\0$]+”
查找模式的第一个和最后一个索引

Pattern pattern = Pattern.compile("\$[^\. \\n$]+");
Matcher matcher = pattern.matcher(string)
if (matcher.find()) {
    start = matcher.start()
    end = matcher.end()
    text = matcher.group()
}
然后换掉绳子的那部分

String st = "Hello $employee.$currency and $bankbalance";
String pattern = "[$]\\w+";
String res = st.replaceAll(pattern,"mystring");
System.out.println(res);
Output=
Hello mystring.mystring和mystring


对于

,您曾经问过与此完全相同的问题,并给出了一些有用的答案。也许你应该尝试用你的母语建立一个编程论坛。pattern.compile(“\$[^\.\\n$]+”;抛出错误,如无效的转义序列(有效的是\b\t\n\f\r\“\'\\”\)是的,我知道如何执行此不同的字符串示例第一个字符串$employee应替换为一个字符串,$currency将替换为另一个字符串st.replace(“$employee”,“str1”).replace($currency”,“str2”);看看
Stringutils
,它还有一个很好的字符串方法集合。