Java: у Меня есть большая строка HTML и потребности извлечь href = “…” текст

я полагаю, что понятие константы является на самом деле синтаксическим сахаром в C#, и что это просто заменяет какое-либо использование имени с литеральным значением

, Что компилятор делает с объектами константы на других языках?

можно использовать только для чтения для изменяемых типов что меня быть оцененными во времени выполнения. См. эта статья для различий.

7
задан Peter Boughton 3 November 2009 в 23:05
поделиться

6 ответов

.* 

This is an greedy operation that will take any character including the quotes.

Try something like:

"href=\"([^\"]*)\""
8
ответ дан 6 December 2019 в 05:55
поделиться

There are two problems with the code you've posted:

Firstly the .* in your regular expression is greedy. This will cause it to match all characters until the last " character that can be found. You can make this match be non-greedy by changing this to .*?.

Secondly, to pick up all the matches, you need to keep iterating with Matcher.find rather than looking for groups. Groups give you access to each parenthesized section of the regex. You however, are looking for each time the whole regular expression matches.

Putting these together gives you the following code which should do what you need:

Pattern p = Pattern.compile("href=\"(.*?)\"", Pattern.DOTALL);
Matcher m = p.matcher(innerHTML);

while (m.find()) 
{
    System.out.println(m.group(1));
}
6
ответ дан 6 December 2019 в 05:55
поделиться

вы можете использовать библиотеку парсера html. jtidy , например, дает вам DOM-модель html, из которой вы можете извлечь все элементы «a» и прочитать их атрибут «href»

2
ответ дан 6 December 2019 в 05:55
поделиться

Regex is great but not the right tool for this particular purpose. Normally you want to use a stackbased parser for this. Have a look at Java HTML parser API's like jTidy.

5
ответ дан 6 December 2019 в 05:55
поделиться

Используйте встроенный синтаксический анализатор. Что-то вроде:

    EditorKit kit = new HTMLEditorKit();
    HTMLDocument doc = (HTMLDocument)kit.createDefaultDocument();
    doc.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
    kit.read(reader, doc, 0);

    HTMLDocument.Iterator it = doc.getIterator(HTML.Tag.A);

    while (it.isValid())
    {
        SimpleAttributeSet s = (SimpleAttributeSet)it.getAttributes();
        String href = (String)s.getAttribute(HTML.Attribute.HREF);
        System.out.println( href );
        it.next();
    }

Или используйте ParserCallback:

import java.io.*;
import java.net.*;
import javax.swing.text.*;
import javax.swing.text.html.parser.*;
import javax.swing.text.html.*;

public class ParserCallbackText extends HTMLEditorKit.ParserCallback
{
    public void handleStartTag(HTML.Tag tag, MutableAttributeSet a, int pos)
    {
        if (tag.equals(HTML.Tag.A))
        {
            String href = (String)a.getAttribute(HTML.Attribute.HREF);
            System.out.println(href);
        }
    }

    public static void main(String[] args)
        throws Exception
    {
        Reader reader = getReader(args[0]);
        ParserCallbackText parser = new ParserCallbackText();
        new ParserDelegator().parse(reader, parser, true);
    }

    static Reader getReader(String uri)
        throws IOException
    {
        // Retrieve from Internet.
        if (uri.startsWith("http:"))
        {
            URLConnection conn = new URL(uri).openConnection();
            return new InputStreamReader(conn.getInputStream());
        }
        // Retrieve from file.
        else
        {
            return new FileReader(uri);
        }
    }
}

Читателем может быть StringReader.

5
ответ дан 6 December 2019 в 05:55
поделиться

"href=\"(.*?)\"" should also work, but I think Kugel's answer will work faster.

1
ответ дан 6 December 2019 в 05:55
поделиться
Другие вопросы по тегам:

Похожие вопросы: