这与:RegEx: Grabbing values between quotation marks。
有关如果有这样的字符串:
HYPERLINK "hyperlink_funda.docx" \l "Sales"
链接上给出的正则表达式
(["'])(?:(?=(\\?))\2.)*?\1
给了我
[" HYPERLINK ", " \l ", " "]
什么正则表达式会返回用引号括起来的值(特别是在\"
标记之间)?
["hyperlink_funda.docx", "Sales"]
使用Java,String.split(String regex)
方式。
答案 0 :(得分:2)
我认为你误解了String.split
方法的本质。它的工作是找到一种通过匹配分隔符的功能来分割字符串的方法,而不是通过匹配要返回的字符串的功能。
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);
答案 1 :(得分:2)
您不应该使用.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
销售
以下是regex demo,此处为online code demo。