簡體   English   中英

使用Java中的正則表達式從url中提取一些內容

[英]Extract some contents from the url using regular expressions in java

我想從此URL http://www.xyz.com/default.aspx提取內容,這是我想使用正則表達式提取的以下內容。

String expr = "
What Regular Expression should I use here    
"; 

Pattern patt = Pattern.compile(expr, Pattern.DOTALL | Pattern.UNIX_LINES);
URL url4 = null;

try {
    url4 = new URL("http://www.xyz.com/default.aspx");                  
} catch (MalformedURLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
System.out.println("Text" +url4);
Matcher m = null;
try {
    m = patt.matcher(getURLContent(url4));
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
System.out.println("Match" +m);

while (m.find()) {
    String stateURL = m.group(1);
    System.out.println("Some Data" +stateURL);
}

public static CharSequence getURLContent(URL url8) throws IOException {
          URLConnection conn = url8.openConnection();
          String encoding = conn.getContentEncoding();
          if (encoding == null) {
            encoding = "ISO-8859-1";
          }
          BufferedReader br = new BufferedReader(new
              InputStreamReader(conn.getInputStream(), encoding));
          StringBuilder sb = new StringBuilder(16384);
          try {
            String line;
            while ((line = br.readLine()) != null) {
              sb.append(line);
              System.out.println(line);
              sb.append('\n');
            }
          } finally {
            br.close();
          }
          return sb;
        }

正如@ bkent314所提到的,與使用正則表達式相比, jsoup是一種更好,更清潔的方法。

如果您查看該網站的源代碼,則基本上需要該片段中的內容:

<div class="smallHd_contentTd">
    <div class="breadcrumb">...</div>
    <h2>Services</h2>
    <p>...</p>
    <p>...</p>
    <p>...</p>
</div>

通過使用jsoup,您的代碼可能看起來像這樣:

Document doc = Jsoup.connect("http://www.ferotech.com/Services/default.aspx").get();

Element content = doc.select("div.smallHd_contentTd").first();

String header = content.select("h2").first().text();

System.out.println(header);

for (Element pTag : content.select("p")) {
    System.out.println(pTag.text());
}

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM