Java中的字符串匹配与替换
我有这样一个字符串:Java中的字符串匹配与替换,java,string,match,string-matching,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
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(生于11月7日的Barbara Jane Huberman),
他是一名计算机科学家。
她目前是麻省理工学院的福特工程教授
工程学院电气工程与计算机科学
系和麻省理工学院教授。
关于您的模式([){1}\\d(]){1}
:
总是无用的,因为它总是隐式的{1}
和[
需要用反斜杠转义(因为它本身必须用另一个反斜杠转义,因为它是字符串文字)]
没有明确的基数,因此例如\\d
将不匹配,因为有两个数字[12]
因此,最好尝试:
\[\\d+\\]
使用stringreplaceall(stringregex,stringreplacement)
您所要做的就是a=a.replaceAll(“\\[\\d+\\]”,“”)
您可以阅读了解更多信息。非常简单:
a = a.replaceAll("\\[\\d+\\]","");
这些变化:
replaceAll
代替replace
[]
-它们是regex特殊字符。伙伴关系并没有摆脱它们{1}
,[{1}
=[
都指定字符应为一次d+
中的+
用于多个数字,如[12]
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);
String a=“Barbara Liskov(1939年11月7日出生于加利福尼亚州的Barbara Jane Huberman)是一名计算机科学家。[2]她目前是麻省理工学院电气工程和计算机科学系的福特工程教授和麻省理工学院的学院教授。[3]”;
对于(int i=1;i