正则表达式:从字符串引号之间拼抢值(RegEx: Grabbing value between qu

2019-10-20 22:43发布

这涉及到: 正则表达式:抓住引号之间的值 。

如果有这样的字符串:

HYPERLINK "hyperlink_funda.docx" \l "Sales"

链接中给出的正则表达式

(["'])(?:(?=(\\?))\2.)*?\1

是给我

[" HYPERLINK ", " \l ", " "]

什么正则表达式将返回值括在引号(特别是与\"标记)?

["hyperlink_funda.docx", "Sales"]

使用Java, String.split(String regex)的方式。

Answer 1:

你不应该使用与.split()方法。 相反,使用Pattern与捕获组:

{
    Pattern pattern = Pattern.compile("([\"'])((?:(?=(\\\\?))\\3.)*?)\\1");
    Matcher matcher = pattern.matcher(" HYPERLINK \"hyperlink_funda.docx\" \\l \"Sales\" ");

    while (matcher.find())
        System.out.println(matcher.group(2));
}

输出:

hyperlink_funda.docx
销售

这是一个正则表达式的演示 ,这里是一个在线演示代码 。



Answer 2:

我想你是误会的性质String.split方法。 它的任务是找到通过匹配分离器的功能,而不是匹配希望返回的字符串的功能分割字符串的方法。

相反,你应该使用PatternMatcher

String txt = " HYPERLINK \"hyperlink_funda.docx\" \\l \"Sales\" ";

String re = "\"([^\"]*)\"";

Pattern p = Pattern.compile(re);
Matcher m = p.matcher(txt);
ArrayList<String> matches = new ArrayList<String>();
while (m.find()) {
    String match = m.group(1);
    matches.add(match);
}
System.out.println(matches);


文章来源: RegEx: Grabbing value between quotation marks from string