用于将带引号的字符串与转义引号相匹配的 Java 正则表达式

发布于 2024-08-26 01:21:01 字数 322 浏览 3 评论 0原文

我知道已经有很多像我这样的问题,但我没有找到适用于 Java 的答案。所以我写了一个新问题。

我有包含如下内容的文本文件:

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

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

瀟灑尐姊 2024-09-02 01:21:01

尝试这个正则表达式:

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

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}))*\""
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文