用于将引用的字符串与转义引号相匹配的Java Regex [英] Java Regex for matching quoted string with escaped quotes

查看:163
本文介绍了用于将引用的字符串与转义引号相匹配的Java Regex的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我已经有很多问题,但是我没有发现任何在Java中有用的答案。所以我写了一个新的问题。



我有这样的内容的文本文件:

 
key1 =这是一个使用'\\'字符转义的\test\文本;
key2 ='它必须使用\'单个'''引号和双引号';

我需要一个与双引号(或单引号)中的值匹配的正则表达式。此正则表达式必须支持转义的引号和转义的反斜杠。
正则表达式必须适用于Java标准模式/匹配器类。

解决方案

请尝试使用此正则表达式:

 '([^ \\'] + | \\([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}))*

作为字符串文字:

   '([^ \\\\'] + | \\\\([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}))* \


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.

解决方案

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}))*\""

这篇关于用于将引用的字符串与转义引号相匹配的Java Regex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆