Java regex throwing exception for no match found when pattern found in line

前端 未结 2 1182
终归单人心
终归单人心 2021-01-04 19:22

I am dying trying to figure out why a regex won\'t match. Any help is much appreciated. I\'m going line by line of a web page (that works fine), but I need to pull out the l

相关标签:
2条回答
  • 2021-01-04 20:03

    Ok, so I figured it out. The only issue was, my regex had to be

    ".*href=\"([^\"]*?)\".*"
    

    Which then made the code

    private String regex = ".*href=\"([^\"]*?)\".*";
    private Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(result);
    if (m.matches()) {
        String urlStr = m.group(1);
        links.add(urlStr);
    }
    

    So that was my issue with the regex, I had to use the '?' to not be greedy I guess!

    0 讨论(0)
  • 2021-01-04 20:08

    first call

    m.find();
    

    or

    m.matches();
    

    and then you'll be able to use m.group() if matcher succeeded.

    0 讨论(0)
提交回复
热议问题