1

I have a json string like this:

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

However, when I use the replace all in 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

1
  • 1
    Do you want to remove other names like "first=, last=, hobby1=,hobby2=" or only the top level names? Commented Jul 17, 2012 at 8:33

2 Answers 2

4

The problem is that the { character is a special character in regex syntax which denotes an amount (for instance \d{2} denotes 2 digits). 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*\\=(?=\\{)";.

For me, this yielded:

{{first=sam, last=vo}, {hobby1=football, hobby2=swimming}}

Sign up to request clarification or add additional context in comments.

Comments

1
java.util.regex.PatternSyntaxException: Illegal repetition

comes because of your "{" in "\\w*\\=(?={)". "{" and "}" are special characters to state characters repetitions as you might know ...

just try to escape it like that "\\w*\\=(?=\\{)". and since you're working with json , please consider using a JSON-Parser like:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.