天天看點

正規表達式 學習筆記1.2

書接上一回:

執行個體三:

資料提取

要求:從一段HTML代碼中提取出所有的email位址和< a href...>tag中的連結位址

public class HtmlTest {

public static void main(String[] args) {

String htmlText = "<html>"

+ "<a href=\"[email protected]\">163test</a>\n"

+ "<a href='[email protected]'>163news</a>\n"

+ "<a href=http://www.163.com>163lady</a>\n"

+ "<a href = http://sports.163.com>網易體育</a>\n"

+ "<a href    = \"http://gz.house.163.com\">網易房産</a>\n"

+ ".leemaster@163" + "luckdog.com" + "</html>";

System.out.println("開始檢查email");

for (String email : extractEmail(htmlText)) {

System.out.println("郵箱是:" + email);

}

System.out.println("開始檢查超連結");

for (String link : extractLink(htmlText)) {

System.out.println("超連結是:" + link);

private static List<String> extractLink(String htmlText) {

List<String> result = new ArrayList<String>();

Pattern p = Pattern.compile(Regexes.HREF_LINK_REGEX);

Matcher m = p.matcher(htmlText);

while (m.find()) {

result.add(m.group());

return result;

private static List<String> extractEmail(String htmlText) {

Pattern p = Pattern.compile(Regexes.EMAIL_REGEX);

public class Regexes {

public static final String EMAIL_REGEX = 

"(?i)(?<=\\b)[a-z0-9][-a-z0-9_.]+[a-z0-9]@([a-z0-9][-a-z0-9]+\\.)+[a-z]{2,4}(?=\\b)";

public static final String HREF_LINK_REGEX 

= "(?i)<a\\s+href\\s*=\\s*['\"]?([^'\"\\s>]+)['\"\\s>]";

運作結果:

開始檢查email

郵箱是:[email protected]

郵箱是:[email protected]

郵箱是:[email protected]

開始檢查超連結

超連結是:<a href="[email protected]"

超連結是:<a href='[email protected]'

超連結是:<a href=http://www.163.com>

超連結是:<a href = http://sports.163.com>

超連結是:<a href    = "http://gz.house.163.com"

執行個體四:

查找重複單詞

要求:查找一段文本中是否存在重複單詞,如果存在,去掉重複單詞。

public class FindWord {

String[] sentences = new String[] { "this is a normal sentence",

"Oh,my god!Duplicate word word",

"This sentence contain no duplicate word words" };

for(String sentence:sentences){

System.out.println("校驗句子:"+sentence);

if(containDupWord(sentence)){

System.out.println("Duplicate word found!!");

System.out.println("正在去除重複單詞"+removeDupWords(sentence));

System.out.println("");

private static String removeDupWords(String sentence) {

String regex = Regexes.DUP_WORD_REGEX;

return sentence.replaceAll(regex,"$1");

private static boolean containDupWord(String sentence) {

Pattern p = Pattern.compile(regex);

Matcher m = p.matcher(sentence);

if(m.find()){

return true;

}else{

return false;

public static final String DUP_WORD_REGEX 

= "(?<=\\b)(\\w+)\\s+\\1(?=\\b)";

校驗句子:this is a normal sentence

校驗句子:Oh,my god!Duplicate word word

Duplicate word found!!

正在去除重複單詞Oh,my god!Duplicate word

校驗句子:This sentence contain no duplicate word words

未完待續。。。

本文轉自jooben 51CTO部落格,原文連結:http://blog.51cto.com/jooben/316592

繼續閱讀