【问题标题】:extract substring between quotation marks ignoring \"提取引号之间的子字符串忽略 \"
【发布时间】:2012-09-05 06:43:03
【问题描述】:

我的文件包含一些行,例如

"This is a string." = "This is a string's content."
" Another \" example \"" = " New example."
"My string
can have several lines." = "My string can have several lines."

我需要提取子字符串:

This is a string.
This is a string's content.
 Another \" example \"
 New example.
My string
can have several lines.
My string can have several lines.

这是我的代码:

String regex = "\".*?\"\\s*?=\\s*?\".*?\"";
Pattern pattern = Pattern.compile(regex,Pattern.DOTALL);
Matcher matcher = pattern.matcher(file);

目前,我可以得到“=”的左右部分。但是当我的子字符串包含“\””时,我的正则表达式就不能正确工作。

谁能帮我写出正确的正则表达式吗?我尝试了 \"^[\\"] 而不是 \",但它没有用..

提前感谢。

【问题讨论】:

    标签: java regex


    【解决方案1】:
    List<String> matchList = new ArrayList<String>();
    Pattern regex = Pattern.compile(
        "\"          # Match a quote\n" +
        "(           # Capture in group number 1:\n" +
        " (?:        # Match either...\n" +
        "  \\\\.     # an escaped character\n" +
        " |          # or\n" +
        "  [^\"\\\\] # any character except quotes or backslashes\n" +
        " )*         # Repeat as needed\n" +
        ")           # End of capturing group\n" +
        "\"          # Match a quote", 
        Pattern.COMMENTS);
    Matcher regexMatcher = regex.matcher(subjectString);
    while (regexMatcher.find()) {
        matchList.add(regexMatcher.group(1));
    } 
    

    【讨论】:

      【解决方案2】:

      很抱歉,我所在的位置无法测试,但可以

      \".*?(?:[^\\]\")\\s*=\\s*\".*?(?:[^\\]\")
      

      工作?

      我刚换了 \"(?:[^\\]\") 因此,如果它们之前的字符不再是 \,它们将不匹配。

      【讨论】:

      • 实际上,stackoverflow 在我的最后一行中踢掉了一些反斜杠,但是您可以在代码行中正确看到它(我希望)
      【解决方案3】:
      /"([^"\\]*(?:\\.[^"\\]*)*)"/
      

      SourceAlso see this previous question.

      【讨论】:

      • 来源其实是Jeffrey Friedl的《Mastering Regular Expressions》(叫《unrolling the loop》)。
      • (另外,他要求的是 Java 正则表达式,这是一个 JavaScript 正则表达式。)
      猜你喜欢
      • 1970-01-01
      • 2011-01-05
      • 2011-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-07
      • 1970-01-01
      • 2014-02-16
      相关资源
      最近更新 更多