【问题标题】:How to use replaceFirst to Replace {....}如何使用 replaceFirst 替换 {....}
【发布时间】:2011-04-14 05:04:29
【问题描述】:

我有一个包含xyaahhfhajfahj{adhadh}fsfhgs{sfsf} 的字符串。

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

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

【问题讨论】:

  • 也许您可以通过示例输出阐明您想要的内容。

标签: java string replace


【解决方案1】:

试试这个:

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

【讨论】:

    【解决方案2】:

    如果您要查找 {} 内第一次出现的任何内容,然后将其替换为包括括号在内的任何内容,下面是一个示例:

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

    【讨论】:

    • 使用否定字符类比惰性量词更有效——例如"\\{[^}]*\\}"
    猜你喜欢
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-18
    • 2016-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多