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”)
就可以了