awestley
awestley

Reputation: 41

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.

Upvotes: 0

Views: 451

Answers (1)

The fourth bird
The fourth bird

Reputation: 163362

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

  • (?: Non capture group
    • \b(MyObject)\h*\{\h* Capture MyObject in group 1 and match {
    • (?=[^{}]*})
    • | Or
    • \G(?!^) Assert the position at the end of the previous match
  • ) Close the non capture group
  • (?: Non capture group
    • (?:nothingSpecial|privateEmail)= Match either nothingSpecial or privateEmail followed by =
    • '([^'\n,]+)' Capture group 2 Match any char except ' a newline or comma between single quotes
    • | Or
    • [^\s=]+='[^'\n,]*' Match a key value pair with single quotes
  • ) Close non capture group
  • (?:,\h*)? Optionally match a comma and horizontal whitespace chars

Upvotes: 1

Related Questions