匹配文本中的網址javaRegex

來源:互聯網
上載者:User

標籤:正則匹配   網址匹配   

原文:匹配文本中的網址javaRegex

原始碼:http://www.zuidaima.com/share/1575653789993984.htm

公司有個業務需要匹配文本中的網址,度娘,穀哥了半天經常看到有對html中擷取超連結的正則,只要匹配<a href=[‘"]?(.*?)[‘"]?即可,但如果是普通文本類型的則比較費事些,分享下最後的運算式:

import java.util.regex.Matcher;import java.util.regex.Pattern;public class URLMatcher {public static void main(String[] args) {Pattern pattern = Pattern.compile("(http://|ftp://|https://|www){0,1}[^\u4e00-\u9fa5\\s]*?\\.(com|net|cn|me|tw|fr)[^\u4e00-\u9fa5\\s]*");// 空格結束Matcher matcher = pattern.matcher("隨碟附送http://www.xxx.com/sdfsdf.htm?aaaa=%ee%sss ?sdfsyyy空格結束");while (matcher.find()) {System.out.println(matcher.group(0));}// 中文結束matcher = pattern.matcher("隨碟附送http://www.xxx.com/sdfsdf.htm?aaaa=%ee%sss網址結束");while (matcher.find()) {System.out.println(matcher.group(0));}// 沒有http://開頭matcher = pattern.matcher("隨碟附送www.xxx.com/sdfsdf.htm?aaaa=%ee%sss網址結束");while (matcher.find()) {System.out.println(matcher.group(0));}// net網域名稱matcher = pattern.matcher("隨碟附送www.xxx.net/sdfsdf.htm?aaaa=%ee%sss網址結束");while (matcher.find()) {System.out.println(matcher.group(0));}// xxx網域名稱matcher = pattern.matcher("隨碟附送www.xxx.xxx/sdfsdf.htm?aaaa=%ee%sss網址結束");while (matcher.find()) {System.out.println(matcher.group(0));}// yyyy網域名稱匹配不到System.out.println("匹配不到yyyy網域名稱");matcher = pattern.matcher("隨碟附送www.xxx.yyyy/sdfsdf.html?aaaa=%ee%sss網址結束");while (matcher.find()) {System.out.println(matcher.group(0));}// 沒有http://www.matcher = pattern.matcher("隨碟附送xxx.com/sdfsdf.html?aaaa=%ee%sss網址結束");while (matcher.find()) {System.out.println(matcher.group(0));}}}

結果是死的,但思路是活的,大家可以根據自己的業務隨意改寫運算式。

有圖有真相:


著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

匹配文本中的網址javaRegex

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.