【问题标题】:How to fetch the link that is outside the href tag?如何获取 href 标签之外的链接?
【发布时间】:2015-04-22 08:50:43
【问题描述】:
private static final Pattern ptninhref =Pattern.compile(
            "(?:.*\\<[aA][^\\>]*(?i)href(?-i)=\\\"[^\\\"]*)([^\\\"]*)");

    public static List<String> captureValuesinhref(String largeText){
        Matcher mtchinhref = ptninhref.matcher(largeText);
        List<String> inHREF = new ArrayList<>();
        while(mtchinhref.find()){
           inHREF.add(mtchinhref.group());

如何只获取"link is given "
当我使用(?:.*\&lt;[aA][^\&gt;]*(?i)href(?-i)=\"[^\"]*)([^\"]*)(?:[^\"]*\".*\&lt;/[aA]\&gt;.*) 这个正则表达式代码时,它会给出如下输出:&lt;a href="link is given here"&gt;link is given here&lt;/a&gt;

但仅需要输出:"link is given here"
我需要在 href 标签之外的链接。

有两个链接:
1 在 href 标记内。
2 在浏览器中显示的 href 标记之外。
我只需要第二个链接。
如何在netbeans中使用java来获取它?

【问题讨论】:

  • 我没有完全理解这个问题,您介意详细说明一下吗?也许添加一些你到目前为止尝试过的代码。
  • 你明白我想问什么了吗?
  • 不,我不明白你的问题。
  • 我想获取一个在 href 标记之外的 URL
  • w3schools.com">VisitW3Schools.com!

标签: java html netbeans web-scraping


【解决方案1】:
public class RegexExample {

    /**
     * @param args
     */
    public static void main(String[] args) {

        String href= "<a href=\"w3schools.com\">Visit W3Schools.com!</a>";
        String regexOr = "(?<=[>])(\\\\?.)*?(?=[<])";
        Pattern pattern = Pattern.compile(regexOr);
        Matcher matcher = pattern.matcher(href);
        if (matcher.find()) {
            String enrichedValue = matcher.group();
            System.out.print(enrichedValue);
        }
    }
}

这将打印:

访问 W3Schools.com!

记住\在java中变成\\,需要转义

完整示例:

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexExample {
    private static final Pattern ptninhref;
    static{
        ptninhref = Pattern.compile("(?<=[>])(\\\\?.)*?(?=[<])");
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        String href= "<a href=\"paypal.com/signin/\">https://www.paypa1.com/signin/</a>";
        List<String> results = captureValuesinhref(href);
        for(String result:results){
            System.out.print(result);
        }
    }

    public static List<String> captureValuesinhref(String largeText){
        Matcher mtchinhref = ptninhref.matcher(largeText);
        List<String> inHREF = new ArrayList<String>();
        while(mtchinhref.find()){
           inHREF.add(mtchinhref.group());
        }
        return inHREF;
    }
}

打印:

https://www.paypa1.com/signin/

【讨论】:

猜你喜欢
  • 2013-10-30
  • 1970-01-01
  • 1970-01-01
  • 2017-09-29
  • 2015-04-14
  • 2011-07-09
  • 2016-02-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多