簡體   English   中英

Java中的字符串匹配和替換

[英]String matching and replace in Java

我有一個像這樣的字符串:

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("");
}

但它不起作用!

你的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.

很簡單:

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

變化:

  1. 使用replaceAll而不是replace

  2. 逃避[] - 他們是正則表達式特殊字符。 伙伴關系並沒有逃避他們。

  3. 你的正則表達式[{1} ==不需要{1} [ - 兩者都指定該字符應該是一次

  4. +添加到d+是用於多於一個的位數的數字,如[12]

關於您的模式([){1}\\\\d(]){1}

  • {1}始終是無用的,因為總是隱含的
  • []需要使用反斜杠進行轉義(因為在字符串文字中,它本身必須使用另一個反斜杠進行轉義)
  • \\\\d沒有明確的基數,所以[12]例如不匹配,因為有兩位數

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

使用String replaceAll(String regex, String replacement)

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

您可以閱讀Javadoc以獲取更多信息。

用這個:

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);

這會奏效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM