Java can';t替换“;{“with replaceAll方法”
我们正在使用字符串的replaceAll方法,不能替换任何字符串中的{。 我们的例子是: 尝试:Java can';t替换“;{“with replaceAll方法”,java,string,methods,replaceall,Java,String,Methods,Replaceall,我们正在使用字符串的replaceAll方法,不能替换任何字符串中的{。 我们的例子是: 尝试: "some { string".replaceAll("{", "other string"); 错误如下: java.util.regex.PatternSyntaxException:发生非法重复 欢迎任何想法!也许有解决办法?!您需要避开{,因为它在正则表达式中有特殊含义。使用: String s = "some { string".replaceAll("\\{", "other stri
"some { string".replaceAll("{", "other string");
错误如下:
java.util.regex.PatternSyntaxException:发生非法重复
欢迎任何想法!也许有解决办法?!您需要避开
{
,因为它在正则表达式中有特殊含义。使用:
String s = "some { string".replaceAll("\\{", "other string");
像这样尝试使用replace()
"some { string".replace("{", "other string");
或者使用以下正则表达式格式的replaceAll
"some { string".replaceAll("\\{", "your string to replace");
注意:在replace()
的情况下,第一个参数是字符序列,但在replaceAll
的情况下,第一个参数是regex使用replaceAll需要
尝试使用replace方法而不是replaceAll
"some { string".replace("{", "other string");
或者使用\\
"some { string".replaceAll("\\{", "other string");
您必须使用转义字符\\
:
"some { string".replaceAll("\\{", "other string");
字符<代码> {< /C> >在正则表达式中保留,这就是为什么必须将它与文本匹配的原因。或者,可以使用<代码>替换< /> >只考虑<代码>字符序列,而不是正则表达式。
需要逃离字符“{”。
试试这个:
"some { string".replaceAll("\\{", "other string");
{是正则表达式引擎的一个指示符,表示您将要启动一个重复指示符,如{2,4},它表示“前一个标记的2到4倍”
但是{f是非法的,因为它后面必须跟一个数字,所以它抛出一个异常
你可以这样做
"some { string".replaceAll("\\{", "other string");
替换:
“xxx”。替换(“{”、“xxx”)
全部替换:
“xxx”。替换(“\{”,“xxx”)
您需要对其进行转义\{
应完成您可能需要转义字符{
的工作。请尝试.replaceAll(“\\{”,“其他字符串”);
除非您试图使用正则表达式,否则您应该使用replace
,而不是replaceAll
replace
替换所有发生的事件,而不仅仅是第一个。请参阅@Korashen@NavneetKrishna@Korashen.replace
和.replaceAll
都会替换所有出现的内容。.replaceAll
是与正则表达式一起使用,并且.replace
没有。老实说,名称约定很糟糕。.replaceAll
和.replaceAllWithRegex
或者类似的东西会更有意义。旁注:还有一个.replaceFirst
方法,与类似。replaceAll
只接受正则表达式,但只会替换第一个出现的。哦,孩子,你是对的。弄混了一些东西…删除了我的评论,因为它是错误的。然后是什么,我想。。。