简体   繁体   English

如何使用Java的String.replaceAll方法替换以$开头的String

[英]How to replace a String starting with $ character using Java's String.replaceAll method

What's the correct regex for a String starting with $ char as the first argument (ie the string to replace) to Java's replaceAll method in the String class? 什么是以$ char开头的String作为String类中Java的replaceAll方法的第一个参数(即要替换的字符串)的正确正则表达式是什么? I can't get the syntax right. 我无法正确理解语法。 Example

String s = "SUMIF($C$6:$C$475,\"   India - Hyd\",K$6:K$475)";
System.out.println(s.replaceAll("$475", "$44"));

在这种情况下,我建议您使用replace()而不是replaceAll() ,因为您没有使用任何正则表达式:

System.out.println(s.replace("$475", "$44"));

这应该工作:

System.out.println(s.replaceAll("\\$475", "\\$44"));

Documentation of string.replace() states that string.replace()文档说明了这一点

public String replace(CharSequence target, CharSequence replacement) public String replace(CharSequence target,CharSequence replacement)

Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. 将与该文字目标序列匹配的此字符串的each子字符串替换为指定的文字替换序列。

So you can use replace method instead of replaceAll. 所以你可以使用replace方法而不是replaceAll。

String s = "SUMIF($C$6:$C$475,\"   India - Hyd\",K$6:K$475)";
System.out.println(s.replace("$475", "$44"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM