【问题标题】:Regex for matching a string literal in Java?用于匹配Java中的字符串文字的正则表达式?
【发布时间】:2016-08-30 04:19:30
【问题描述】:

我有一个正则表达式字符串数组。其中之一必须匹配在给定 java 文件中找到的任何字符串。

这是我目前拥有的正则表达式字符串:"(\").*[^\"].*(\")"

但是,即使字符串中的引号被转义,字符串"Hello\"good day" 也会被拒绝。我认为当我在内部找到引号时,我会立即拒绝字符串文字,无论它是否被转义。我需要它接受带有转义引号的字符串文字,但它应该拒绝"Hello"Good day"

  Pattern regex = Pattern.compile("(\").*[^\"].*(\")", Pattern.DOTALL);
  Matcher matcher = regex.matcher("Hello\"good day");
  matcher.find(0); //false

【问题讨论】:

  • 您可能想对" 字符进行否定的后视。但是你将很难与 cmets 打交道。
  • 另外你说'"Hello\"good day"被拒绝'然后你说'但它应该拒绝"Hello"Good day"'。这意味着它正在工作。
  • 我需要它接受带有转义引号的字符串文字,但它应该拒绝 "Hello"Good day" - 你必须指的是像 String pat = "\"[^\\\\\"]*(?:\\\\.[^\"\\\\]*)*\"" 这样的正则表达式,并将它与 String#matches() 一起使用。编辑:查看 anubhava 刚刚发布的内容。
  • 您需要担心其他转义序列吗? \n, \t, \u1234?

标签: java regex regex-greedy


【解决方案1】:

在 Java 中,您可以使用此正则表达式匹配 "" 之间的所有转义引号:

boolean valid = input.matches("\"[^\"\\\\]*(\\\\.[^\"\\\\]*)*\"");

使用的正则表达式是:

^"[^"\\]*(\\.[^"\\]*)*"$

分手:

^             # line start
"             # match literal "
[^"\\]*       # match 0 or more of any char that is not " and \
(             # start a group
   \\         # match a backslash \
   .          # match any character after \
   [^"\\]*    # match 0 or more of any char that is not " and \
)*            # group end, and * makes it possible to match 0 or more occurrances
"             # match literal "
$             # line end

RegEx Demo

【讨论】:

  • 模式正则表达式 = Pattern.compile("\"([^\"\\\]*)(\\\\.[^\"\\\]*)*\"",图案.DOTALL); Matcher matcher = regex.matcher("Hello\"good day"); boolean result=matcher.find(0); //当我这样使用你的正则表达式字符串时,我得到了错误。我怎样才能让它工作
  • 如果使用集群组而不是捕获会稍微快一些。
猜你喜欢
  • 2011-06-24
  • 1970-01-01
  • 1970-01-01
  • 2013-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多