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

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

String ReplaceAll() method is not giving proper results

问题

  1. 这是我的代码片段
  2. public class Test {
  3. public static void main(String[] args) {
  4. String s = "sourav /*the parameter*/ /*the parameter*/ /*the parameter*/";
  5. if (true) {
  6. s = s.replaceAll("\\/\\*the parameter\\*\\/", "111");
  7. System.out.println(s);
  8. }
  9. }
  10. }
  11. "由于replaceAll()方法接受正则表达式,我使用了转义序列,但仍然没有被转义。"
  12. "我得到的响应是 sourav /*111 /*111 /*111"
  13. "期望得到的响应是 sourav 111 111 111"
  14. "我知道可以用简单的replace()方法来实现。但是我能用replaceAll()方法来做吗?请告诉我。"
英文:

"This is the snippet of my code"

  1. public class Test {
  2. public static void main(String[] args) {
  3. String s = "sourav /*the patameter*/ /*the patameter*/ /*the patameter*/";
  4. if (true) {
  5. s = s.replaceAll("\\/*the patameter\\*/", "111");
  6. System.out.println(s);
  7. }
  8. }
  9. }

"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

尝试:

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

或者更好的方法:

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

Try:

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

Or even better:

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

答案2

得分: 0

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

  1. 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.

  1. 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:

确定