Reputation: 41
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
Don't match since it's not MyObject
: YourObject{nothingSpecial='Word1', secretData='Word2', privateEmail='Word3'}
Match to MyObject so look for nothingSpecial & privateEmail: MyObject { nothingSpecial='Word1', secretData='Word2', privateEmail='Word3'}
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
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*)?
(?:
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 charsUpvotes: 1