Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使用replaceFirst替换{….}_Java_String_Replace - Fatal编程技术网

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

Java 如何使用replaceFirst替换{….},java,string,replace,Java,String,Replace,我有一个字符串,它包含xyaahhfhajfahj{adhadh}fsfhgs{sfsfsf} 现在我想用空格替换{string}。 我想用null替换其中的花括号和字符串 我想使用replaceFirst,但我不知道使用哪个正则表达式。如果你说你想找到{和}中的任何内容的第一次出现,然后将其包括括号在内的内容替换为空,下面的示例可以做到这一点: String input = "xyaahhfhajfahj{adhadh}fsfhgs{sfsf}"; String output = input.

我有一个字符串,它包含
xyaahhfhajfahj{adhadh}fsfhgs{sfsfsf}

现在我想用空格替换
{string}

我想用null替换其中的花括号和字符串


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

如果你说你想找到
{
}
中的任何内容的第一次出现,然后将其包括括号在内的内容替换为空,下面的示例可以做到这一点:

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

如果您想查找
{
}
中的任何内容的第一次出现,请将其替换为不包含括号的内容,下面是一个示例:

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

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);
    }
}
试试这个:

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

也许你可以用一个示例输出阐明你想要什么。也许你可以用一个示例输出阐明你想要什么。使用负字符类比惰性量词更有效——例如
“\\{[^}]*\\}”
。使用负字符类比惰性量词更有效——例如
“\{[^}]*\}”