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