简体   繁体   English

当模式在行中找到时,Java正则表达式抛出异常,找不到匹配项

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

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. 应用程序将检查该行中是否有链接,但我需要实际提取URL。 help? 救命?

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. 即使'result'中有一个链接引用(hxxp://www.yahoo.com)。

links is an ArrayList fyi. links是一个ArrayList fyi。 Thanks in advance! 提前致谢!

first call 第一次打电话

m.find();

or 要么

m.matches();

and then you'll be able to use m.group() if matcher succeeded. 然后,如果匹配器成功,您将能够使用m.group()

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! 我猜不要贪心!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM