【问题标题】:How to replace a substring with ( from a string如何用(从字符串中替换子字符串
【发布时间】:2015-11-13 18:04:27
【问题描述】:

我有如下字符串

Want to Start (A) Programming and (B) Designing

我想用\n(A) 替换(A) 和用\n(B) 替换(B) 所以,预期的结果会是这样的

Want to Start
(A) Programming and 
(B) Designing

我试过了

stringcontent=stringcontent.replaceAll("(A)", "\n(A)");

它不工作。在谷歌搜索后,我意识到这是因为字符串中有特殊字符(和)。

有什么办法可以解决吗?

【问题讨论】:

  • 特殊字符&在哪里?!
  • 您是否进一步阅读了这些字符的特殊之处以及您如何处理它?全部在 replaceAll() 的文档中
  • 我的意思是 - ( & )。希望你明白我的意思。
  • @NitzRaj (&) 具有误导性。
  • (和):P。不要提及:作为误导:D

标签: java android string replace


【解决方案1】:

这个正则表达式

String a = "Want to Start (A) Programming and (B) Designing";
String b = a.replaceAll("\\(", "\n\\(");
System.out.println(b);

结果

Want to Start 
(A) Programming and 
(B) Designing

只需用\\ 转义括号就可以了。

编辑: 更具体,如下所述

a.replaceAll("(\\([AB]\\))", "\n$1"); 仅匹配 (A) 和 (B) 或

a.replaceAll("(\\(\\w\\))", "\n$1"); 匹配任何 (*)(单词字符)

【讨论】:

  • 根据问题,您可能应该将正则表达式修改为 "(\(\w\))" 并将替换为 "\n$1",以便它只匹配问题所要求的参数。
【解决方案2】:

你必须转义特殊字符:

stringcontent=stringcontent.replaceAll("\\(A\\)", "\n(A)");

【讨论】:

  • 谢谢老兄的正确答案。这里才是真正的 stringcontent=stringcontent.replaceAll("\(A\)", "\n\(A\)");
【解决方案3】:

作为第一个参数方法 replaceAll 需要正则表达式,我强烈建议您阅读它们。

stringcontent.replaceAll("\\((?=\\w\\))", "\n(");

编辑:

建议的答案使用硬编码字母进行检查和替换(或假设大括号中没有文本)。我的答案使用与字母匹配的 \w 通配符以及高级检查,以确保字母和右大括号跟随您的左大括号。 使用什么答案取决于您。

【讨论】:

    猜你喜欢
    • 2017-03-23
    • 1970-01-01
    • 2018-07-07
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 2014-06-09
    • 2020-04-05
    相关资源
    最近更新 更多