如何用 ( 从字符串中替换子字符串 [英] How to replace a substring with ( from a string

查看:49
本文介绍了如何用 ( 从字符串中替换子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像下面这样的字符串

I have a string like following

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

我想将 (A) 替换为 \n(A) 并将 (B) 替换为 \n(B)所以,预期的结果会像

I want to replace (A) with \n(A) and (B) with \n(B) So ,the expected result will be like

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

我试过了

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

它不起作用.在谷歌搜索后,我意识到这是因为字符串中的特殊字符().

It's not working. After searching in google, I realized its because of special characters ( and ) in string.

有没有办法解决这个问题?

Any possible way to solve this?

推荐答案

这个正则表达式

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

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

Just escape the brackets with \\ and you're fine.

更具体,如下所述

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

a.replaceAll("(\\([AB]\\))", "\n$1"); to match only (A) and (B) or

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

a.replaceAll("(\\(\\w\\))", "\n$1"); to match any (*) (Word character)

这篇关于如何用 ( 从字符串中替换子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆