在线找到模式时,Java regex 抛出异常,因为找不到匹配项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22633951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:57:55  来源:igfitidea点击:

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

javaregexmatcher

提问by johwiltb

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 links for each line. The application will check to see if there is a link in the line, but I need to actually pull out the URL. help?

我很想弄清楚为什么正则表达式不匹配。任何帮助深表感谢。我将逐行浏览网页(效果很好),但我需要拉出每一行的链接。应用程序将检查该行中是否有链接,但我需要实际拉出 URL。帮助?

Pattern p = Pattern.compile("^.*href=\"([^\"]*)");
Matcher m = p.matcher(result);
String urlStr = m.group();
links.add(urlStr);

The error message I keep getting is this:

我不断收到的错误消息是这样的:

Exception in thread "main" java.lang.IllegalStateException: No match found
at java.util.regex.Matcher.group(Matcher.java:485)

Even though 'result' has a link reference (hxxp://www.yahoo.com) in it.

即使“结果”中有一个链接参考(hxxp://www.yahoo.com)。

links is an ArrayList fyi. Thanks in advance!

链接是一个 ArrayList 仅供参考。提前致谢!

采纳答案by johwiltb

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!

所以这是我对正则表达式的问题,我不得不使用 '?' 我想不要贪婪!

回答by Sergey Fedorov

first call

第一个电话

m.find();

or

或者

m.matches();

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

然后m.group()如果匹配器成功,您就可以使用。