字符串的`ReplaceAll()`方法未能给出正确的结果。

huangapple go评论61阅读模式
英文:

String ReplaceAll() method is not giving proper results

问题

这是我的代码片段

    public class Test {
        public static void main(String[] args) {
            String s = "sourav /*the parameter*/ /*the parameter*/ /*the parameter*/";
            if (true) {
                s = s.replaceAll("\\/\\*the parameter\\*\\/", "111");
                System.out.println(s);
            }
        }
    }

"由于replaceAll()方法接受正则表达式,我使用了转义序列,但仍然没有被转义。"
"我得到的响应是 sourav /*111 /*111 /*111"

"期望得到的响应是 sourav 111 111 111"
"我知道可以用简单的replace()方法来实现。但是我能用replaceAll()方法来做吗?请告诉我。"
英文:

"This is the snippet of my code"

public class Test {
	public static void main(String[] args) {
		String s = "sourav /*the patameter*/ /*the patameter*/ /*the patameter*/";
		if (true) {
			s = s.replaceAll("\\/*the patameter\\*/", "111");
			System.out.println(s);
		}
	}
}

"As replaceAll() method takes a regex i gave the escape sequence ,Still it is not getting escaped."
"The response i am getting is sourav /*111 /*111 /*111"

"Expected response is sourav 111 111 111".
"I know this can be done with simple replace() method .But can i do it with replaceAll().Please Let me know"

答案1

得分: 0

尝试:

s.replaceAll("/*the patameter*/", "111");

或者更好的方法:

s.replace("/*the patameter*/", "111");
英文:

Try:

s.replaceAll("/\\*the patameter\\*/", "111");

Or even better:

s.replace("/*the patameter*/", "111");

答案2

得分: 0

尝试使用 \Q 和 \E 开关。这是在正则表达式模式中声明字符串文字(转义)的方式。

s = s.replaceAll("\\Q/*the parameter\\*/\\E", "111");
英文:

Try using the \Q and \E switches. It's the way to declare a string literal (escape) within the regex pattern.

s = s.replaceAll("\\Q/*the patameter\\*/\\E", "111");

huangapple
  • 本文由 发表于 2020年10月16日 22:37:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/64391261.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定