harryparis
harryparis

Reputation: 23

How to match one word only within double quotes

I was trying to match one word within double quotes but not outside. For instance:

"xxxxxxxxxxxxxx " , OneWord ; OneWord, "xxxxx , OneWord xxxxx". " OneWord 1" ----  " OneWord 2":

The expected match I need is
"xxxxx , OneWord xxxxx"
" OneWord 1"
" OneWord 2"

I had tried this

"(?:(?!OneWord)[^"])*(?(?=")\"\K|OneWord[^"]*")

Finally, I realized that the quotes not containing the OneWord match and it's just not showed. ex:"xxxxxxxxxxxxxx ". it matches but not showed. What I need is just to have the quotes containing the OneWord matched.

Is that possible?

Upvotes: 2

Views: 58

Answers (1)

The fourth bird
The fourth bird

Reputation: 163597

You could use

"[^"]*\bOneWord\b[^"]*"(?=(?:[^"]*"[^"]*")*[^"]*$)

Explanation

  • "[^"]* Match " followed by 0+ occurrences of any char except "
  • \bOneWord\b Match OneWord between word boundaries
  • [^"]*" Match 0+ occurrences of any char except ", then match "
  • (?= Positive lookahead, assert what is at the right
    • (?:[^"]*"[^"]*")* Optionally match pairs of double quotes
    • [^"]*$ Match an optional trailing part without " till the end of the string
  • ) Close lookahead

Regex demo

Or a bit longer version accepting an escaped double quote

Regex demo

Upvotes: 1

Related Questions