javaregex

Regex Pattern Match toString() in Java


I'm looking for some help with matching a pattern for a string (tostring() generated):

MyObject{nothingSpecial='Word1', secretData='Word2', privateEmail='Word3'}

I wanted a pattern that can match on the Word1, Word3. So I came up with:

(?x)(["]?(nothingSpecial|secretData)["]?\s*[:=]{1}\s*["]?)(?:[^"\n,]+)

That worked but now I need to step it up so I can match on the oject name too e.g. MyObject

Examples:

  1. Don't match since it's not MyObject: YourObject{nothingSpecial='Word1', secretData='Word2', privateEmail='Word3'}

  2. Match to MyObject so look for nothingSpecial & privateEmail: MyObject { nothingSpecial='Word1', secretData='Word2', privateEmail='Word3'}

  3. Don't match since it's not MyObject: TheirObject{nothingSpecial='Word1', secretData='Word2', privateEmail='Word3'}

Truthfully, I've never been great a RegEx so any help would be very much appreciated.


Solution

  • To match the 3 words, you could make use if the \G anchor

    (?:\b(MyObject)\h*\{\h*(?=[^{}]*})|\G(?!^))(?:(?:nothingSpecial|privateEmail)='([^'\n,]+)'|[^\s=]+='[^'\n,]*')(?:,\h*)?
    

    Regex demo | Java demo