Reputation: 591
I need to match a text within a text that is surrounded by two characters, in this case ‘ and ’. So assume that the whole string is:
Regarding the cat, I asked him ‘can you take care of my cat while I am away’ and he said ‘yes’.
Now, if I use the following regex
(?<=‘)(.*?)(?=’)
It will match
can you take care of my cat while I am away
and
yes
What if I want to search for a single character e.g. "e" (matches in both quoted strings) or word e.g. "cat" within those two groups? How can I do that? I cannot figure out how to replace (.*?) in order to search for a substring/character within those special quotes.
Upvotes: 2
Views: 78
Reputation: 89567
You only need to replace the dot that is too permissive with a class that excludes the closing quote and the first character of your target:
(?<=‘)([^’e]*(e)[^’]*)(?=’)
or
(?<=‘)([^’c]*(?:(?:\Bc|c(?!at\b))[^’c]*)*\b(cat)\b[^’]*)(?=’)
Upvotes: 2