简体   繁体   English

Java正则表达式:根据先前字符匹配字符

[英]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: 我可以创建2个子,但我认为它不是最佳的:

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

Any hint would be greatly appreciated, thanks! 任何提示将不胜感激,谢谢!

You can use back reference \\n (eg \\1 - for the first capturing group, \\2 for the second) 您可以使用反向引用\\n (例如, \\1用于第一个捕获组, \\2用于第二个捕获组)

So your example would look like: 因此,您的示例如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM