Tom Tom - 1 year ago 47
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:


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


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


Any hint would be greatly appreciated, thanks!

Answer Source

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

So your example would look like: