Java Regex for matching quoted string with escaped quotes

妖精的绣舞 提交于 2019-12-18 03:39:31

问题


I know there are already many questions like mine but I found no answer which works in Java. So I write a new question.

I have text files with content like this:

key1 = "This is a \"test\" text with escapes using '\\' characters";
key2 = 'It must work with \'single\' quotes and "double" quotes';

I need a regular expression which matches the values in the double-quotes (or single-quotes). This regular expression must support the escaped quotes and escaped backslashes. The regular expression must work with Java standard Pattern/Matcher classes.


回答1:


Try this regular expression:

'([^\\']+|\\([btnfr"'\\]|[0-3]?[0-7]{1,2}|u[0-9a-fA-F]{4}))*'|"([^\\"]+|\\([btnfr"'\\]|[0-3]?[0-7]{1,2}|u[0-9a-fA-F]{4}))*"

And as a string literal:

"'([^\\\\']+|\\\\([btnfr\"'\\\\]|[0-3]?[0-7]{1,2}|u[0-9a-fA-F]{4}))*'|\"([^\\\\\"]+|\\\\([btnfr\"'\\\\]|[0-3]?[0-7]{1,2}|u[0-9a-fA-F]{4}))*\""


来源:https://stackoverflow.com/questions/2498635/java-regex-for-matching-quoted-string-with-escaped-quotes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!