Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/388.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/amazon-s3/2.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 String ReplaceAll方法给出非法重复错误?_Java_Regex_String_Replaceall - Fatal编程技术网

Java String ReplaceAll方法给出非法重复错误?

Java String ReplaceAll方法给出非法重复错误?,java,regex,string,replaceall,Java,Regex,String,Replaceall,我有一个字符串,当我尝试运行replaceAll方法时,我遇到了一个奇怪的错误: String str = "something { } , op"; str = str.replaceAll("o", "\n"); // it works fine str = str.replaceAll("{", "\n"); // does not work Exception in thread "main" java.util.regex.PatternSyntaxException: Illega

我有一个字符串,当我尝试运行
replaceAll
方法时,我遇到了一个奇怪的错误:

String str = "something { } , op";
str = str.replaceAll("o", "\n"); // it works fine
str = str.replaceAll("{", "\n"); // does not work
Exception in thread "main" java.util.regex.PatternSyntaxException:
Illegal repetition {  
我得到一个奇怪的错误:

String str = "something { } , op";
str = str.replaceAll("o", "\n"); // it works fine
str = str.replaceAll("{", "\n"); // does not work
Exception in thread "main" java.util.regex.PatternSyntaxException:
Illegal repetition {  
如何替换出现的
“{”

转义它:

str = str.replaceAll("\\{", "\n"); 

这是必需的,因为到的第一个参数是a,
{
在Java正则表达式中有特殊的含义(它是一个重复运算符,因此是错误消息)。a
{
是一个正则表达式元字符,用于范围重复,如
{min,max}
,以匹配文本
{
您需要在它前面加一个
\\
来转义它:

str = str.replaceAll("\\{", "\n"); // does work

如果您真的想替换单个字符而不是正则表达式(这似乎是您在这里想要做的),您应该使用
.replace()
,而不是
.replaceAll()
。不管它的名称如何,
.replace()
将替换所有出现的字符,而不仅仅是第一个

如果您想知道,
String
实现了
CharSequence
,那么
.replace(“{”,“\n”)
就可以了