Tom Tom - 6 months ago 11
Java Question

Java regex: match character based on previous character

How to match a closing quote (single or double) depending on opening quote used?

For now I have:

key.*?=["'].*?["']


But unfortunately the closing quote is not dependent on the opening one and it won't work for the following example:

key="foo'bar"


I could created 2 sub but I assume that it isn't optimal:

key.*?=(".*?"|'.*?')


Any hint would be greatly appreciated, thanks!

Answer

You can use back reference \n (e.g. \1 - for the first capturing group, \2 for the second)

So your example would look like:

key.*?=(["']).*?\1