Java正则表达式的几个应用实例(匹配网址,匹配美国安全码,匹配日期)

由于最近做的项目需要从英文文本中提取出字符串进行话题的聚类,于是就花了一天的时间来学习Java正则表达式,一下几个小例子是我的一些小练笔,如有不合理之处,还望各位指教!!

1.此例是用来过滤掉英文文本中的网址,并将过滤后的字符串输出

首先需要先贴出来我需要过滤的英文文本,我将这些文本存在一个名为englishtxt.txt中,其内容为

  

 1 www.baidu.com
 2 银行挤兑:可能引发下一轮金融危机的盲点 http://mp.weixin.qq.com/s?__biz=MjM5MDY4Mzg2MA==&mid=200223248&idx=1&sn=a5b668754a60a8e07f335bd59521fb03#rd?…
 3 Beijing CBD right now 01 pic.twitter.com/zCNP4CFrrk
 4 I see more and more Chinese ask the same question online: what if most #MH370 passengers were Americans; how would the US government react?
 5 10:27:01 Chinese Net friend expectations http://chinafree.greatzhonghua.org/showthread.php?tid=5377?… Chinese Net friend expectations -...
 6 01:47:01 Times silly and fantastic notions, Gu Xiaojun Thought Yiu glorious http://chinafree.greatzhonghua.org/showthread.php?tid=4969?… T...
 7 [強國空氣問題比愛滋更嚴重] China Smog at Center of <<Air Pollution Deaths Cited>> by WHO http://bloom.bg/1rqNRBP? /via @BloombergNews
 8 [Android 高登仔] LIHK 已重生,你會花 HK$10 買嗎? https://play.google.com/store/apps/details?id=com.lihk.hkgolden.app.reborn?…
 9 #Taiwan protests: Water cannons are an indiscriminate tool for dispersing protesters & can result in serious injury
10 NASA 的新太空衣... http://jscfeatures.jsc.nasa.gov/z2/?
11 PHOTOS: Marijuana through the years http://ow.ly/uXzuq? (AP Photo/DEA) pic.twitter.com/4LSP4nlLMQ
12 Protest in Taiwan http://blog.flickr.net/en/2014/03/24/protest-in-taiwan/?… /via @flickr
13 [原來昨天說的那位嬰兒已經...] Baby born on board diverted Cathay flight dies http://www.scmp.com/news/hong-kong/article/1456417/baby-born-board-diverted-cathay-flight-dies?… /via @SCMP_News
14 What does Apple think about the lack of diversity in emojis? We have their response. http://on.mtv.com/OWu6D7? /via @MTVact
15 Linkin Park releases customizable music video powered by Xbox‘s Project Spark http://www.theverge.com/2014/3/25/5546982/linkin-park-releases-customizable-music-video-powered-by-xboxs?…
16 Full draw for @afcasiancup 2015 is here pic.twitter.com/nrYJo1mm9G #AC2015
17 Interesting draw RT @afcasiancup: Group B: Saudi Arabia, China PR, DPR Korea, Uzbekistan #AC2015
18 Finally: @emirates are activating their Twitter account.
19 Interior Minister Prince Mohammed bin Naif launches new ministry site aboard what appears like a private jet —SPA pic.twitter.com/NDSGJVbXTs

  从该文本文档中我们可以看出,文本中存在大量的网址,如果直接拿来进行话题聚类的话,会产生大量的噪声数据,于是需要去除这些网址,于是我的代码如下

  

 1 import java.io.BufferedReader;
 2 import java.io.File;
 3 import java.io.FileNotFoundException;
 4 import java.io.FileReader;
 5 import java.io.IOException;
 6 import java.util.regex.Matcher;
 7 import java.util.regex.Pattern;
 8
 9 public class URLMatcher {
10     public static void main(String[] args) throws IOException {
11             BufferedReader br = new BufferedReader(new FileReader(new File("D://englishtxt.txt")));
12             System.out.println("开始从文本中读数据");
13             String line = br.readLine();
14             while(line!=null)
15             {
17                 String value = line.replaceAll("(http://|https://|ftp://)?(\\w+\\.)+\\w+(:\\d*)?([^#\\s]*)","").replaceAll("[\\/?:;[email protected]#$%^&*+()【】<<>>...-]", "");
18                 StringBuilder strb = new StringBuilder();
19                 Pattern ptn = Pattern.compile("\\w+");
20                 Matcher mch = ptn.matcher(value);
21                 while(mch.find())
22                 {
23                     strb.append(mch.group());
24                     strb.append(" ");
25                 }
26                 System.out.println(strb.toString());
27                 line = br.readLine();
28             }
29
30    }
31 }    

上面代码的功能不仅能够过滤掉大量的网址,还可以去除一些特殊的标点符号

 运行的结果如下:

开始从文本中读数据

rd
Beijing CBD right now
I see more and more Chinese ask the same question online what if most MH passengers were Americans how would the US government react
Chinese Net friend expectations Chinese Net friend expectations
Times silly and fantastic notions Gu Xiaojun Thought Yiu glorious T
China Smog at Center of Air Pollution Deaths Cited by WHO via BloombergNews
Android LIHK HK I
Taiwan protests Water cannons are an indiscriminate tool for dispersing protesters can result in serious injury
NASA
PHOTOS Marijuana through the years AP PhotoDEA
Protest in Taiwan via flickr
f Baby born on board diverted Cathay flight dies via SCMP News
What does Apple think about the lack of diversity in emojis We have their response via MTVact
Linkin Park releases customizable music video powered by Xbox s Project Spark
Full draw for afcasiancup is here AC
Interesting draw RT afcasiancup Group B Saudi Arabia China PR DPR Korea Uzbekistan AC
Finally emirates are activating their Twitter account
Interior Minister Prince Mohammed bin Naif launches new ministry site aboard what appears like a private jet SPA 

从上面的结果可以看出,网址基本都被过滤出来了。

2.下面的这个小例子是用来匹配美国的安全码

代码如下:

            String safeNum = "This is a safe num 999-99-9999,this is the second num 456003348,this is the third num 456-909090,this is the forth num 45677-0764";
            Pattern ptn = Pattern.compile("\\d{3}\\-?\\d{2}\\-?\\d{4}");
            Matcher mch = ptn.matcher(safeNum);
            while(mch.find())
            {
                System.out.println(mch.group());
            }

最后的输出结果为:

999-99-9999
456003348
456-909090
45677-0764

3.这个小例子是用来匹配英文中的日期

            String strDate = "this is a date June 26,1951";
            Pattern ptn = Pattern.compile("([a-zA-Z]+)\\s[0-9]{1,2},\\s*[0-9]{4}");
            Matcher mch = ptn.matcher(strDate);
            while(mch.find())
            {
                System.out.println(mch.group());
            }

输出结果为:

June 26,1951

以上的这3个小例子就是我在学正则表达式的时候做的小练笔,希望对大家的学习有所帮助!!

时间: 2024-08-08 09:41:42

Java正则表达式的几个应用实例(匹配网址,匹配美国安全码,匹配日期)的相关文章

java正则表达式语法详解及其使用代码实例

原文地址 译者序(下载代码) 正则表达式善于处理文本,对匹配.搜索和替换等操作都有意想不到的作用.正因如此,正则表达式现在是作为程序员七种基本技能之一*,因此学习和使用它在工作中都能达到很高的效率. 正则表达式应用于程序设计语言中,首次是出现在 Perl 语言,这也让 Perl 奠定了正则表达式旗手的地位.现在,它已经深入到了所有的程序设计语言中,在程序设计语言中,正则表达式可以说是标准配置了. Java 中从 JDK 1.4 开始增加了对正则表达式的支持,至此正则表达式成为了 Java 中的基

java正则表达式匹配所有数字

用于匹配的正则表达式为 :([1-9]\d*\.?\d*)|(0\.\d*[1-9]) ( [1-9] :匹配1~9的数字: \d :匹配数字,包括0~9: * :紧跟在 \d 之后,表明可以匹配零个及多个数字: \. :匹配小数点: ? :紧跟在 \. 之后,表明可以匹配零个或一个小数点: 0 :匹配一个数字0: )其中的 [1-9]\d*\.?\d* 用以匹配诸如:1.23.34.0.56.78 之类的非负的整数和浮点数: 其中的 0\.\d*[1-9] 用以匹配诸如:0.1.0.23.0.

Java 正则表达式 向前、向后匹配

//向后匹配 String a = "I paid $90 for 10 oranges, 12 pears and 8 apples. I saved $5 on "; Pattern p = Pattern.compile("(?<=\\$)\\d+"); Matcher m = p.matcher(a); while (m.find ()) { String group = m.group (); System.out.println (group);

Java正则表达式实例详解

创建正则表达式 你可以从比较简单的东西入手学习正则表达式.要想全面地掌握怎样构建正则表达式,可以去看JDK 文档的java.util.regex 的Pattern 类的文档. 字符 B 字符B \xhh 16进制值0xhh 所表示的字符 \uhhhh 16进制值0xhhhh 所表示的Unicode字符 \t Tab \n 换行符 \r 回车符 \f 换页符 \e Escape 正则表达式的强大体现在它能定义字符集(character class).下面是一些最常见的字符集及其定义的方式,此外还有

Java正则表达式匹配多行

默认情况下.*中的.只能匹配出\n以外的字符,如果遇到要匹配的字符串包含回车换行符(多行),则正则表达式遇到换行符后会停止,导致包含回车换行符的串不能正确匹配,解决的办法是: 1.使用Pattern和Matcher对象 设置Pattern模式为:Pattern.DOTALL 2.使用String.replaceAll() 正则表达式写法: String reg = "(?s)'.*'"; 下面是一个包含回车换行字符的正则表达式替换处理例子. static String teststr

Java 正则表达式匹配邮箱地址

作者 : 卿笃军 正则表达式中的部分元字符: 元字符 正则表达式中的写法 意义 . . 代表任意一个字符 \d \\d 代表0~9的任何一个数字 \D \\D 代表任何一个非数字字符 \s \\s 代表空白字符,如:'\t','\n' \S \\S 代表非空白字符 \w \\w 代表柯用作标示符的字符,单不包括'$' \W \\W 代表不可用作标示符的字符 . . 正则表达式,限定修饰符: 限定修饰符 意义 示例 ? 0次或1次 A? * 0次或多次 A* + 1次或多次 A+ {n} 正好出现

匹配文本中的网址java正则表达式

原文:匹配文本中的网址java正则表达式 源代码下载地址:http://www.zuidaima.com/share/1575653789993984.htm 公司有个业务需要匹配文本中的网址,度娘,谷哥了半天经常看到有对html中获取超链接的正则,只要匹配<a href=['"]?(.*?)['"]?即可,但如果是普通文本类型的则比较费事些,分享下最后的表达式: import java.util.regex.Matcher; import java.util.regex.Pat

java正则表达式 match、find匹配位置

如题,对于java正则表达式这几个方法匹配一次后的,匹配位置搞不太清楚,就写了几个例子.如下: String ss="ooaaoo"; Pattern pt=Pattern.compile("(o+)"); Matcher mt=pt.matcher(ss); // mt.lookingAt(); // mt.matches(); while(mt.find()){ System.out.println(mt.group(1)+"|||"+mt.

Java 正则表达式 量词 --- 三种匹配模式【贪婪型、勉强型、占有型】

1.Greediness(贪婪型):最大匹配X?.X*.X+.X{n,}都是最大匹配.例如你要用“<.+>”去匹配“a<tr>aava</tr>abb”,也许你所期待的结果是想匹配“<tr>”,但是实际结果却会匹配到“<tr>aava</tr>”.这是为什么呢?下面我们跟踪下最大匹配的匹配过程.①“<”匹配字符串的“<”.②“.+”匹配字符串的“tr>aava</tr>ab”,在进行最大匹配时,它把两个“