开发者

Searching for a tag, then saving text between tag as a variable

I'm quite new to Java, but how would I go about searching a file for a tag, then everything between the tags, like a string of text, would be assigned to a variable.

For example, I'd have <title>THE TITLE</title>, But then I wanted to save the string "THE TITLE" to a variable called title1, o开发者_如何学Cr something.

How should I go about doing that? Thank you.


If you use regular expressions, then you just use a capture group:

Pattern p = Pattern.compile("<title>([^<]*)</title>", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(theText);
if (m.find()) {
    String thisIsTheTextYouWant = m.group(1);
    ....


You should not use regex to parse HTML: RegEx match open tags except XHTML self-contained tags

Try jsoup http://jsoup.org/cookbook/extracting-data/attributes-text-html

String html = "<title>THE TITLE</title>";
Document doc = Jsoup.parse(html);
Element title = doc.select("title").first();
String result = title.text();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜