[英]Java; String replaceAll giving error
I want to replace "{
from below String
: 我想替换
"{
from below String
:
public static void main(String args[]){
String input="Subtitle,\"{\"key\": \"IsReprint\", \"value\":\"COPY\"}";
input=input.replaceAll("\"{", "{"));
System.out.println("String ::::"+input);
}
I'm getting this error: 我收到这个错误:
Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition near index 1
\"{
^
You have two ways: 你有两种方式:
The first you have to escape the {
with \\\\{
, because replaceAll use regex so you have to escape the "
and {
: 第一个你必须逃避
{
with \\\\{
,因为replaceAll使用正则表达式,所以你必须逃避"
和{
:
input=input.replaceAll("\"\\{", "{");
The second is to use replace
instead if you don't have this complicated regex : 第二种是使用
replace
如果你没有这个复杂的正则表达式:
input=input.replace("\"{", "{");
replaceAll
takes a regex as an argument. replaceAll
将正则表达式作为参数。 {
has a special meaning in regex, so have to escape {
by doing {
在正则表达式中有特殊含义,所以必须逃避{
通过做
input=input.replaceAll("\"\\{", "{");
or use replace
, which doesn't take a regex as an argument. 或者使用
replace
,它不会将正则表达式作为参数。
input=input.replace("\"{", "{");
You are not escaping the "{" character correctly when you are calling replaceAll. 当您调用replaceAll时,您没有正确转义“{”字符。
You need to use "two slashes" \\\\ before any regular expression (regExp). 你需要在任何正则表达式(regExp)之前使用“两个斜杠”\\\\。
Here is an example: 这是一个例子:
public static void main(String args[]){
String input="Subtitle,\"{\"key\": \"IsReprint\", \"value\":\"COPY\"}";
System.out.println(input.replaceAll("\\{", "*"));
}
My example replaces the "{" character with a *: 我的示例用*替换“{”字符:
"\\{", "*"
Running , you get the ouput: 跑步 ,你得到的输出:
Subtitle,"*"key": "IsReprint", "value":"COPY"}
With the input: 随着输入:
String input="{{ }}";
You get the output: 你得到输出:
** }}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.