如何为这种情况编写正则表达式?

时间:2010-03-24 18:22:29

标签: java regex

我想知道如何为以下代码编写正则表达式。

<a href="/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。

1 个答案:

答案 0 :(得分:1)

txt2re有一个很好的工具可以用来轻松生成各种语言的正则表达式。 我用它来generate以下内容:

import java.util.regex.*;

class Main
{
  public static void main(String[] args)
  {
    String txt="<a href=\"/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");
    }
  }
}
相关问题