Java中的字符串匹配和替换

时间:2014-06-24 10:11:43

标签: java string match string-matching

我有一个像这样的字符串:

String a = "Barbara Liskov (born Barbara Jane Huberman on November 7, 1939"
+" in California) is a computer scientist.[2] She is currently the Ford"
+" Professor of Engineering in the MIT School of Engineering's electrical"
+" engineering and computer science department and an institute professor"
+" at the Massachusetts Institute of Technology.[3]";

我想替换所有这些元素:[1][2][3]等等,并留空格。

我尝试过:

if (a.matches("([){1}\\d(]){1}")) {
    a = a.replace("");
}

但它不起作用!

5 个答案:

答案 0 :(得分:10)

你的Pattern都错了。

试试这个例子:

String input = 
      "Barbara Liskov (born Barbara Jane Huberman on November 7, 1939 in California) "
    + "is a computer scientist.[2] She is currently the Ford Professor of Engineering "
    + "in the MIT School of Engineering's electrical engineering and computer "
    + "science department and an institute professor at the Massachusetts Institute " 
    + "of Technology.[3]";
//                                   | escaped opening square bracket
//                                   |  | any digit
//                                   |  |   | escaped closing square bracket
//                                   |  |   |      | replace with one space
System.out.println(input.replaceAll("\\[\\d+\\]", " "));

输出(为清晰起见添加了换行符)

Barbara Liskov (born Barbara Jane Huberman on November 7, 
1939 in California) is a computer scientist. 
She is currently the Ford Professor of Engineering in the MIT 
School of Engineering's electrical engineering and computer science 
department and an institute professor at the Massachusetts Institute of Technology.

答案 1 :(得分:3)

很简单:

   a = a.replaceAll("\\[\\d+\\]","");

变化:

  1. 使用replaceAll代替replace

  2. 逃离[] - 他们是正则表达式特殊字符。伙伴关系并没有逃脱它们。

  3. 您的正则表达式{1} == [{1}无需[ - 两者都指定该字符应该是一次

  4. +添加到d+的数字超过一位数,例如[12]

答案 2 :(得分:2)

关于您的模式([){1}\\d(]){1}

  • {1}总是无用的,因为总是隐含的
  • []需要使用反斜杠进行转义(因为在字符串文字中,它本身必须使用另一个反斜杠进行转义)
  • \\d没有明确的基数,因此[12]因为有两位数而赢了匹配

所以,最好试试:\\[\\d+\\]

答案 3 :(得分:0)

使用String replaceAll(String regex, String replacement)

你所要做的就是a=a.replaceAll("\\[\\d+\\]", " ")

您可以阅读Javadoc了解详情。

答案 4 :(得分:0)

使用此:

String a = "Barbara Liskov (born Barbara Jane Huberman on November 7, 1939 in California) is a computer scientist.[2] She is currently the Ford Professor of Engineering in the MIT School of Engineering's electrical engineering and computer science department and an institute professor at the Massachusetts Institute of Technology.[3]";

        for(int i =1 ; i<= 3; i++){
               a= a.replace("["+i+"]","");
        }
        System.out.println(a);

这样可行。