java - Java中的字符串匹配和替换

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

但是它不起作用!

最佳答案

你的模式完全错误。

试试这个例子:

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.

关于java - Java中的字符串匹配和替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24383939/

相关文章:

php - Mysql 全文搜索与匹配和反对

design-patterns - 在 F# 中 float 的整数列表

java - 一次从 Eclipse 运行两个 Java 程序?

java - 在 Clojure REPL 中使用自定义 Java 类

c# - 如何计算字符串中特定字符的集合

java - 从每行中删除特定文本

java - 手动更新数据库后清除 Hibernate 二级缓存

java - 如何使我的 tictactoe 程序具有可扩展性

c - 如何使用 MPI C 文件中的索引修改字符串?

php - 忽略 preg_match_all 输出中的字符