[英]string.replaceAll java doesn't work with lookaround regex?
I have a json string like this: 我有一个像这样的json字符串:
string = "{name={first=sam, last=vo}, hobbies={hobby1=football, hobby2=swimming}}"
And I want to remove the "name=" and the "hobbies=", so that I use this pattern: \\w*\\=(?={)
->tested using editPadPro 我想删除“ name =“和“ hobby” =”,以便使用以下模式:
\\w*\\=(?={)
->使用editPadPro测试
However, when I use the replace all in java: 但是,当我在Java中使用全部替换时:
String pattern = "\\w*\\=(?={)";
String removedParent = string.replaceAll(pattern, "");
I got this error message 我收到此错误消息
"Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition near index 7
\w*\=(?={)"
Can you please give me some advices to get this work? 您能给我一些建议来完成这项工作吗?
Regards, 问候,
Sam 山姆
The problem is that the {
character is a special character in regex syntax which denotes an amount (for instance \\d{2}
denotes 2 digits). 问题是
{
字符是正则表达式语法中的特殊字符,表示一个数字(例如\\d{2}
表示2位数字)。 In your case, you want to match the literal {
, meaning that you need to escape the {
character, so you need to change your regex to this: "\\\\w*\\\\=(?=\\\\{)";
在您的情况下,您想要匹配文字
{
,这意味着您需要转义 {
字符,因此您需要将正则表达式更改为: "\\\\w*\\\\=(?=\\\\{)";
. 。
For me, this yielded: 对我来说,这产生了:
{{first=sam, last=vo}, {hobby1=football, hobby2=swimming}}
{{first = sam,last = vo},{hobby1 = football,hobby2 = swimming}}
java.util.regex.PatternSyntaxException: Illegal repetition
comes because of your "{" in "\\\\w*\\\\=(?={)"
. 的出现是因为您在
"\\\\w*\\\\=(?={)"
。 "{" and "}" are special characters to state characters repetitions as you might know ... 如您所知,“ {”和“}”是特殊字符,用于说明字符重复...
just try to escape it like that "\\\\w*\\\\=(?=\\\\{)"
. 只需尝试像
"\\\\w*\\\\=(?=\\\\{)"
那样对其进行转义即可。 and since you're working with json , please consider using a JSON-Parser like: 并且由于您使用的是json,请考虑使用JSON-Parser,例如:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.