【发布时间】:2011-04-14 05:04:29
【问题描述】:
我有一个包含xyaahhfhajfahj{adhadh}fsfhgs{sfsf} 的字符串。
现在我想用空格替换{string}。
我想用 null 替换大括号和其中的字符串。
我想使用replaceFirst,但我不知道使用正则表达式。
【问题讨论】:
-
也许您可以通过示例输出阐明您想要的内容。
我有一个包含xyaahhfhajfahj{adhadh}fsfhgs{sfsf} 的字符串。
现在我想用空格替换{string}。
我想用 null 替换大括号和其中的字符串。
我想使用replaceFirst,但我不知道使用正则表达式。
【问题讨论】:
试试这个:
public class TestCls {
public static void main(String[] args) {
String str = "xyaahhfhajfahj{adhadh}fsfhgs{sfsf}";
String str1 = str.replaceAll("\\{[a-zA-z0-9]*\\}", " ");// to replace string within "{" & "}" with " ".
String str2 = str.replaceFirst("\\{[a-zA-z0-9]*\\}", " ");// to replace first string within "{" & "}" with " ".
System.out.println(str1);
System.out.println(str2);
}
}
【讨论】:
如果您要查找 { 和 } 内第一次出现的任何内容,然后将其替换为包括括号在内的任何内容,下面是一个示例:
String input = "xyaahhfhajfahj{adhadh}fsfhgs{sfsf}";
String output = input.replaceFirst("\\{.*?\\}", "");
System.out.println(output ); // output will be "xyaahhfhajfahjfsfhgs{sfsf}"
【讨论】:
"\\{[^}]*\\}"。