温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在Java中使用正则表达式对象实现一个获取功能

发布时间:2021-02-19 15:41:50 来源:亿速云 阅读:188 作者:Leah 栏目:互联网科技

本篇文章为大家展示了如何在Java中使用正则表达式对象实现一个获取功能,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

获取需要使用到正则的两个对象:

使用的是用正则对象Pattern 和匹配器Matcher。

用法:

范例:

 Pattern p = Pattern.compile("a*b");  Matcher m = p.matcher("aaaaab");  boolean b = m.matches();

步骤:

1,先将正则表达式编译成正则对象。使用的是Pattern类一个静态的方法。compile(regex);

2,让正则对象和要操作的字符串相关联,通过matcher方法完成,并返回匹配器对象。

3,通过匹配器对象的方法将正则模式作用到字符串上对字符串进行针对性的功能操作

需求:获取由3个字母组成的单词。

public static void getDemo() {   String str = "da jia zhu yi le,ming tian bu fang jia,xie xie!";   //想要获取由3个字母组成的单词。   //刚才的功能返回的都是一个结果,只有split返回的是数组,但是它是把规则作为分隔符,不会获取符合规则的内容。   //这时我们要用到一些正则对象。   String reg = "\\b[a-z]{3}\\b";   Pattern p = Pattern.compile(reg);   Matcher m = p.matcher(str);   while(m.find())   {     System.out.println(m.start()+"...."+m.end());     System.out.println("sub:"+str.substring(m.start(),m.end()));     System.out.println(m.group());   } //   System.out.println(m.find());//将规则对字符串进行匹配查找。 //   System.out.println(m.find());//将规则对字符串进行匹配查找。 //   System.out.println(m.group());//在使用group方法之前,必须要先找,找到了才可以取。 }

校验邮件

public static void checkMail() {   String mail = "abc123@sina.com.cn";   mail = "1@1.1";   String reg = "[a-zA-Z_0-9]+@[a-zA-Z0-9]+(\\.[a-zA-Z]+)+";   reg = "\\w+@\\w+(\\.\\w+)+";//简化的规则。笼统的匹配。   boolean b = mail.matches(reg);   System.out.println(mail+":"+b); }

网络爬虫 (获取邮箱)

class GetMailList  { public static void main(String[] args) throws Exception {   String reg = "\\w+@[a-zA-Z]+(\\.[a-zA-Z]+)+";   getMailsByWeb(reg); } public static void getMailsByWeb(String regex)throws Exception {   URL url = new URL("http://localhost:8080/myweb/mail.html");   URLConnection conn = url.openConnection();   BufferedReader bufIn = new BufferedReader(new InputStreamReader(conn.getInputStream()));   String line = null;   Pattern p = Pattern.compile(regex);      while((line=bufIn.readLine())!=null)   {     //System.out.println(line);     Matcher m = p.matcher(line);     while(m.find())     {       System.out.println(m.group());     }   }   bufIn.close(); } public static void getMails(String regex)throws Exception {   BufferedReader bufr =      new BufferedReader(new FileReader("mail.txt"));   String line = null;   Pattern p = Pattern.compile(regex);      while((line=bufr.readLine())!=null)   {     //System.out.println(line);     Matcher m = p.matcher(line);     while(m.find())     {       System.out.println(m.group());     }   }   bufr.close(); } }

单词边界匹配器 \b

\b代表一个单词的开始和结束部分,不匹配任何字符

上述内容就是如何在Java中使用正则表达式对象实现一个获取功能,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI