如何使用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}"