Java 如何用(从字符串)替换子字符串
我有一根像下面这样的线Java 如何用(从字符串)替换子字符串,java,android,string,replace,Java,Android,String,Replace,我有一根像下面这样的线 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)"); 它不工作。在谷歌搜索后,我意识到它是因为字符串中的特殊字符(和) 有什么可能的解决
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)");
它不工作。在谷歌搜索后,我意识到它是因为字符串中的特殊字符(
和)
有什么可能的解决方法吗?这个正则表达式
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”);
要匹配任何(*)(单词字符)必须转义特殊字符:
stringcontent=stringcontent.replaceAll("\\(A\\)", "\n(A)");
作为第一个参数,replaceAll方法需要正则表达式,我强烈建议您阅读它们
stringcontent.replaceAll("\\((?=\\w\\))", "\n(");
编辑:
建议的答案使用硬编码字母进行检查和替换(或假设大括号中没有文本)。我的答案使用与字母匹配的\w通配符以及高级检查,以确保字母和右大括号紧跟左大括号。
使用什么答案取决于您。特殊字符在哪里&?!您是否进一步阅读了这些字符的特殊之处以及如何处理这些字符?我的意思是-(&)。希望您理解我的意思。@NitzRaj
(&)
有误导性:P.不要提及:误导性:通过这个问题,您可能应该将正则表达式修改为“(\(\w\)”,替换项修改为“\n$1”,这样它只匹配问题所要求的参数。谢谢,这是一个比较正确的答案。这是真正的一个stringcontent=stringcontent.replaceAll(\(A\),“\n\(A\)”;