2017-03-20 7 views
1

私はRegexをjavaに書いて、/ wikiで始まるすべてのwikiリンクを見つけ出し、htmlソースコード中の段落タグの最初の出現の後に出現させようとしています。ウェブページJavaで正規表現を作成してwikiリンクを抽出する

<a href="/wiki/Computer_scientist" title="Computer scientist">computer scientist</a> 
<p>Its fields can be divided into a variety of theoretical and <a href="/wiki/Practical_disciplines" 

例えばこれは私が私が思い付いたもの正規表現ではなく、いくつかの研究を行った後にあまり慣れていないよ/ Practical_disciplines

を/ Wikiを取り出すべきことである。

ArrayList<String> wikiLinks = new ArrayList<String>(); 
Pattern wikiPattern = Pattern.compile("^<p>([a-zA-Z0-9+&@/%?<>\"=~_|!,.;])+^(/wiki/[a-zA-Z0-9+&@/%?=~_|!,.;]+"); 
    Matcher wikiMatcher = wikiPattern.matcher("srcString"); 
    while (wikiMatcher.find()) { 
     wikiLinks.add(srcString.substring(wikiMatcher.start(0), 
      wikiMatcher.end(0))); 

私が知っていますこれは形成が不十分で、大丈夫ではない。しかし、誰かが私にこれのための正規表現を策定したり、正しい方向に私を導くのを助けることができたら、私は本当にそれを感謝します。あなたはこの正規表現を使用することができます

+1

[ jSoup](https://jsoup.org/)組み込みの検索機能を持っています – MadProgrammer

+1

正規表現は、入力HTMLがパターンに一致するように正確に書かれているかどうかを確かめることができます。あなたがそのレベルのコントロールを持っている状況があります。正規表現を使用することは、間違ったアプローチです。したがって、あなたのコンテキストに応じて、真のHTMLパーサを使用する方が良いと思わないかどうかを検討してください。 – GhostCat

答えて

0

...

<p>.*?href=\"(.*?)\" 

は見regex demo/explanation

Javaの私はより多くのようなものを使用してお勧めしたいdemo

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

class RegEx { 
    public static void main(String[] args) { 
     String s = "<a href=\"/wiki/Computer_scientist\" title=\"Computer scientist\">computer scientist</a> <p>Its fields can be divided into a variety of theoretical and <a href=\"/wiki/Practical_disciplines\""; 
     String r = "<p>.*?href=\"(.*?)\""; 
     Pattern p = Pattern.compile(r); 
     Matcher m = p.matcher(s); 
     while (m.find()) { 
      System.out.println(m.group(1)); 
     } 
    } 
} 
+0

説明にリンクを提供してくれてありがとう、本当に助けてくれてありがとう! – smriti

関連する問題