如何使用replaceFirst替换{....}

时间:2011-04-14 05:04:29

标签: java string replace

我的字符串包含xyaahhfhajfahj{adhadh}fsfhgs{sfsf}

现在我想用空格替换{string} 我想用null替换大括号和其中的字符串。

我想使用replaceFirst,但我不知道这样做的正则表达式。

2 个答案:

答案 0 :(得分:3)

试试这个:

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

答案 1 :(得分:2)

如果你想要在{}内找到第一个出现的内容,那么将其替换为包括没有任何内容的括号,这是一个可以做到这一点的示例:< / p>

String input = "xyaahhfhajfahj{adhadh}fsfhgs{sfsf}";
String output = input.replaceFirst("\\{.*?\\}", "");
System.out.println(output ); // output will be "xyaahhfhajfahjfsfhgs{sfsf}"
相关问题