我想从下面的字符串中删除(标题)的每一次出现。我该怎么写一个正则表达式?我试过像下面的正则表达式,但它不起作用。
String ruler1="115.28(54)(title) is renumbered 115.363(title) and amended to read:";
Pattern rulerPattern1 = Pattern.compile("(.*)\\(title\\)(.*)", Pattern.MULTILINE);
System.out.println(rulerPattern1.matcher(ruler1).replaceAll(""));
答案 0 :(得分:3)
正则表达式比这简单得多 - 你需要的只是逃避括号,如下所示:
\\(title\\)
您无需明确使用Pattern
类,因为replaceAll
takes a regular expression。
String ruler1="115.28(54)(title) is renumbered 115.363(title) and amended to read:";
String result = ruler1.replaceAll("\\(title\\)", "");
您的模式会替换包含"(title)"
答案 1 :(得分:1)
只需使用String
提供的内容:
System.out.println(ruler1.replace("(title)", ""));
不要被其名称与.replaceAll()
所愚弄,这是非常误导性的:
.replace()
不使用正则表达式; .replace()
替换所有出现次数。鉴于你需要做什么,这是一个完美的契合。 Javadoc for .replace()
答案 2 :(得分:0)
我不认为正则表达式对于这么简单的事情来说是一个很好的解决方案。尝试使用Apache commons-lang包中的StringUtils.replace()。
String result = StringUtils.replace(ruler1,"(title)","");