2010-03-24 88 views
0

我想知道如何为以下代码编写正则表达式。如何为这种情况编写正则表达式?

<a href="https://stackoverflow.com/search?q=user:111111+[apple]" class="post-tag" title="show all posts by this user in 'apple'">Apple</a><span class="item-multiplier">&times;&nbsp;171</span><br> 

我只需要从上面的源代码中提取Apple。

+6

http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – kennytm 2010-03-24 18:23:28

+0

KennyTM ,虽然你不能使用正则表达式解析HTML,但这个问题不是解析HTML,而是解析一个标签,这当然是可能的。 – 2010-03-24 18:29:35

回答

1

txt2re有一个很好的工具,可以用来简单地生成各种语言的正则表达式。 我把它用来generate如下:

import java.util.regex.*; 

class Main 
{ 
    public static void main(String[] args) 
    { 
    String txt="<a href=\"https://stackoverflow.com/search?q=user:111111+[apple]\" class=\"post-tag\" title=\"show all posts by this user in 'apple'\">Apple</a><span class=\"item-multiplier\">&times;&nbsp;171</span><br>"; 

    String re1=".*?"; // Non-greedy match on filler 
    String re2="(?:[a-z][a-z]+)"; // Uninteresting: word 
    String re3=".*?"; // Non-greedy match on filler 
    String re4="(?:[a-z][a-z]+)"; // Uninteresting: word 
    String re5=".*?"; // Non-greedy match on filler 
    String re6="(?:[a-z][a-z]+)"; // Uninteresting: word 
    String re7=".*?"; // Non-greedy match on filler 
    String re8="((?:[a-z][a-z]+))"; // Word 1 

    Pattern p = Pattern.compile(re1+re2+re3+re4+re5+re6+re7+re8,Pattern.CASE_INSENSITIVE | Pattern.DOTALL); 
    Matcher m = p.matcher(txt); 
    if (m.find()) 
    { 
     String word1=m.group(1); 
     System.out.print("("+word1.toString()+")"+"\n"); 
    } 
    } 
}