RegEx: Grabbing value between quotation marks from string

回眸只為那壹抹淺笑 提交于 2019-12-11 07:44:39

问题


This is related to: RegEx: Grabbing values between quotation marks.

If there is a String like this:

HYPERLINK "hyperlink_funda.docx" \l "Sales"

The regex given on the link

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

is giving me

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

What regex will return values enclosed in quotation mark (specifically between the \" marks) ?

["hyperlink_funda.docx", "Sales"]

Using Java, String.split(String regex) way.


回答1:


You're not supposed to use that with .split() method. Instead use a Pattern with capturing groups:

{
    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));
}

Output:

hyperlink_funda.docx
Sales

Here is a regex demo, and here is an online code demo.




回答2:


I think you are misunderstanding the nature of the String.split method. Its job is to find a way of splitting a string by matching the features of the separator, not by matching features of the strings you want returned.

Instead you should use a Pattern and a Matcher:

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);


来源:https://stackoverflow.com/questions/25787073/regex-grabbing-value-between-quotation-marks-from-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!