JAVA正则表达式

正则表达式

基本概念和语法:
  • 概念:正确规则的表达式,一门独立的语法,很多语言都支持,作用用来定义一些规则,对数据进行校验。是指一个用来描述或者匹配一系列符合某个句法规则的字符串的单个字符串。其实就是一种规则。有自己特殊的应用。
  • 语法:JAVA中用字符串来定义正则。
  • 单个字符匹配(待匹配的字符串只有一个字符)示例:
    String regx = "b";  //用来匹配单个字符
    regx = "[a,b,c,d,e,f,g]";//这个集合中所罗列的的任意一个字符
    regx = "[a-z]";
    regx = "[A,B,C]";
    regx = "[A-Z]";
    regx = "[0-9]";
    regx = "[a-zA-Z0-9]";
    regx = "[^a-z]"; //不是(a-z)的任意一个,^去反符号
    regx = ".";//匹配单个任意字符
    regx = "\\.";// \\ 转义字符   只匹配点本身
    regx = "a|b"; // | 代表或者
    regx = "\\|";//代表 竖线  转义
    regx = "\\d"; // 跟[0-9] 意思一样
    regx = "\\w";//跟 [a-zA-Z_0-9] 意思一样
    boolean b = "12314a".matches(regx); //equals()方法
    
    具体规则可以通过JAVA手册查看Pattern(模式类)的说明即可看到!
  • 多个字符匹配(待匹配的字符串有多个字符):
    regx = "a+b+"; //+代表一个或多个
    boolean b = "aaab".matches(regx) //返回true
    regx = "[a-z]+"; //包含a-z的任意字符,出现1次以上
    regx = "a*"; // *代表0次或多次 
    regx = "a?" //?0次或一次
    regx = "[a-zA-Z]{5}" //正好5次(出现五个字符)
    regx = "[0-9a-z]{5,}"//至少出现5次
    regx = "[0-9a-z]{5,15}"//至少出现5次,最多出现15次
    
  • 边界匹配器:
    ^ 行的开头 
    $ 行的结尾 
    \\b 单词边界
    
    问题1:这里的\b怎么理解?
    回答:
    String str="da jia ting wo shuo, jin tian yao xia yu, bu shang wan zi xi, gao xing bu?hah;sfd.ddd,zzz";
    类似于:
    da 
    jia 
    ting
    ...
    hah
    sdf
    ddd
    zzz
    这些单词都能被这个\\b所匹配到,相当于自动拆分了单词,这个\\b常用于“模式器、匹配器中!”
    
    问题2:这里的开头和结尾符号都没怎么说,怎么用呢?
    (好像JAVA中不需要指明^和$,但在JS中需要这么做????)
实践案例:(验证qq号:)
  • 示例代码:
    /*  需求:校验qq号码.
           1:要求必须是5 - 15 位数字
           2:0 不能开头*/
        String qqRegx = "[1-9][0-9]{4,14}";
        System.out.println("583783842".matches(qqRegx));
        ------------------
        输出:
        true
    
    
实践案例:(校验邮箱!)
  • 题目:校验邮箱:6~18个字符,可使用字母、数字、下划线,需要以字母开头
  • 代码:
	String regx = "[a-zA-Z]\\w{5,17}@163\\.(com|net|cn|org)";
  • 小结:个人感觉,这里的正则主要就是利用正则表达式的规则,来写出一个匹配字符串的模板(它本身就代表了一类的字符串),然后用这个模板去对其他的字符串进行匹配,看其他字符串是否满足模板的需求,从而来返回true or false!
功能部分:
  • 根据正则来截取字符串:
//普通方法:
str.substring(0,str.indexOf("="));
str.substring(str.indexOf("=")+1,str.lastIndexOf("="))
str.substring(str.lastIndexOf("=")+1)
------------------------------
//根据正则来截字符串:
String[] strings = str.split("=")
System.out.println(Arrays.toString(strings));
String str = "我喜欢你=asdf54稀罕你=dsd123123爱死你";
String[] split = str.split("[=a-z0-9]+")
--------------
输出:
[我喜欢你, 稀罕你, 爱死你]
  • 案例:
public class Deom {
    public static void main(String[] args) {
        /* A:
        案例演示:
        需求:我有如下一个字符串:”91 27 46 38 50”,请写代码实现最终输出结果是:”27 38 46 50 91”*/
        String str="91    27    46    38       50";
        //经过你的改造后变成 ==>  "27 38 46 50 91"
        String[] result = str.split("[ ]+");
//        System.out.println(Arrays.toString(result));
        int[] ints = new int[result.length];
        for(int i=0;i<result.length;i++){
            ints[i] = Integer.parseInt(result[i]);
        }
        Arrays.sort(ints);
        String sss = Arrays.toString(ints).replace(",", " ");
        System.out.println(sss.substring(sss.indexOf('[')+1,sss.indexOf(']')));
    }
}
-------------------------
输出:
27  38  46  50  91
  • 根据正则表达式来替换:
String str = "asdfss asdfasdf asdfsadfa    asdfasdf asdf asdf asdfsdfsdf";
String s = str.replaceAll("[ ]+",""); 这个比普通的替换更为强大,正则版本的!
模式器和匹配器(也是与正则相关的两个东东)
  • 概念:Pattern 模式器:用来封装正则表达式
Pattern p = Pattern.compile("a*b"); //将正则表达式封装成一个模式器
  • 用模式器来获取一个匹配器(匹配器:Matcher),把待匹配的字符串传入
Matcher m = p.matcher("aaab");
//调用匹配器中的匹配方法,进行匹配!
boolean b = m.matches();
----------------
输出:
true
  • 为何要用模式器和匹配器?
    我们上面的操作中,都是利用字符串类的matches方法来达到正则匹配的效果,但是如果想做更多的工作,比如:提取符合正则表达式的字符串,我们利用字符串的matches方法是无法达到此效果的,而模式器、匹配器提供了更为丰富的操作接口来进行操作!

  • 案例:获取出下面字符串中是三个字母组成的单词:

public class MyTest2 {
    public static void main(String[] args) {
        //需求:获取出,下面字符串中 是三个字母组成的单词
      String str="da jia ting wo shuo, jin tian yao xia yu, bu shang wan zi xi, gao xing bu?";
      //定义是三个字母组成的单词的正则
        String regx="\\b[a-z]{3}\\b";

      /*
        String[] strings = str.split("[^a-z]+");
        //System.out.println(Arrays.toString(strings));
        for (int i = 0; i < strings.length; i++) {
            if(strings[i].length()==3){
                System.out.println(strings[i]);
            }
        }
        */
        //把正则表达式封装进模式器
        Pattern p = Pattern.compile(regx);
        //根据模式器或取匹配器,传入待操作的数据
        Matcher matcher = p.matcher(str);

      /*  boolean find ()
        尝试查找与该模式匹配的输入序列的下一个子序列。*/
      /*  boolean b = matcher.find();
        System.out.println(b);*/

       /* String group () //截取出符合正则的数据
        返回由以前匹配操作所匹配的输入子序列。*/
       /*
        String s = matcher.group();
        System.out.println(s);

        b = matcher.find();
        System.out.println(b);

        s = matcher.group();
        System.out.println(s);*/

       while (matcher.find()){
           String group = matcher.group();
           System.out.println(group);
       }
    }
}
---------------
输出:
jia
jin
yao
xia
wan
gao
  • 案例:模拟简单解析HTML(爬虫!)
public class MyTest3 {
    public static void main(String[] args) {
        //爬虫:
        String str="<div id=\"SI_Top_Wrap\" class=\"top-nav-wrap\">\n" +
                "                <div class=\"top-nav\">\n" +
                "                    <div class=\"tn-bg\">\n" +
                "                        <div class=\"tn-header\">\n" +
                "                            <div class=\"tn-nav\">\n" +
                "                                <div class=\"tn-title\" node-type=\"sethome\">\n" +
                "                                    <a href=\"javascript:;\" class=\"tn-tab\" suda-uatrack=\"key=index_new_menu&value=set_index\"><i>设为首页</i>\n" +
                "                                    </a>\n" +
                "                                </div>\n" +
                "                                <div class=\"tn-title\" node-type=\"menu\" style=\"display:none;\">\n" +
                "                                    <a href=\"javascript:;\" class=\"tn-tab\">\n" +
                "                                        <i>\n" +
                "                                            我的菜单\n" +
                "                                            <span class=\"tn-arrow\"> </span> </i>\n" +
                "                                    </a>\n" +
                "                                    <div style=\"display:none;\" class=\"tn-topmenulist tn-topmenulist-a tn-topmenulist-a-menu\" node-type=\"menuList\">\n" +
                "                                    </div>\n" +
                "                                </div>\n" +
                "                                <div class=\"tn-title\">\n" +
                "                                    <a target=\"_blank\" href=\"http://tech.sina.com.cn/z/sinawap/\" class=\"tn-tab\" suda-uatrack=\"key=index_new_menu&value=sina_wap\"><i>手机新浪网</i>\n" +
                "                                    </a>\n" +
                "                                </div>\n" +
                "                                <div class=\"tn-title\" node-type=\"client\">\n" +
                "                                    <a target=\"_blank\" class=\"tn-tab\" suda-uatrack=\"key=index_new_menu&value=sina_apps_click\"> <i>移动客户端\n" +
                "<em class=\"tn-new tn-new2\" style=\"display: none; /* display: inline-block; */\"></em>\n" +
                "                                            <span class=\"tn-arrow\"> </span></i> </a>\n" +
                "                                    <div style=\"display:none;\" class=\"tn-topmenulist tn-topmenulist-a tn-topmenulist-a-client\" node-type=\"clientList\">\n" +
                "                                        <ul class=\"tn-text-list\">\n" +
                "<li><a target=\"_blank\" href=\"http://m.weibo.com/web/cellphone.php#iphone\"  suda-uatrack=\"key=index_new_menu&value=sina_apps_list_click\">新浪微博</a></li>\n" +
                "\n" +
                "<li><a target=\"_blank\" href=\"http://news.sina.com.cn/m/sinanews.html\"  suda-uatrack=\"key=index_new_menu&value=sina_apps_list_click\">新浪新闻</a></li>\n" +
                "<li><a target=\"_blank\" href=\"http://finance.sina.com.cn/mobile/comfinanceweb.shtml\"  suda-uatrack=\"key=index_new_menu&value=sina_apps_list_click\">新浪财经</a></li>\n" +
                "<li><a target=\"_blank\" href=\"http://m.sina.com.cn/m/sinasports.shtml\"  suda-uatrack=\"key=index_new_menu&value=sina_apps_list_click\">新浪体育</a></li>\n" +
                "\n" +
                "<li><a target=\"_blank\" href=\"http://edu.sina.com.cn/app/download.shtml\" suda-uatrack=\"key=index_new_menu&value=sina_apps_list_click\">新浪升学帮</a></li>\n" +
                "<li><a target=\"_blank\" href=\"http://licaishi.sina.com.cn/html5/act/ganggu/index.html\"  suda-uatrack=\"key=index_new_menu&value=sina_apps_list_click\">新浪港股通</a></li>\n" +
                "\t\t\t\t\t\t\t\t\t\t\t\n" +
                "<li><a target=\"_blank\" href=\"http://blog.sina.com.cn/lm/z/app/\"  suda-uatrack=\"key=index_new_menu&value=sina_apps_list_click\">新浪博客</a></li>\n" +
                "\n" +
                "<li><a target=\"_blank\" href=\"http://tianqitong.sina.cn/\"  suda-uatrack=\"key=index_new_menu&value=sina_apps_list_click\">天气通</a></li>\n" +
                "\n" +
                "<li><a target=\"_blank\" href=\"http://games.sina.com.cn/o/kb/12392.shtml\"  suda-uatrack=\"key=index_new_menu&value=sina_apps_list_click\">新浪游戏</a></li>\n" +
                "<li><a target=\"_blank\" href=\"http://zhongce.sina.com.cn/about/app\"  suda-uatrack=\"key=index_new_menu&value=sina_apps_list_click\">新浪众测</a></li>\n" +
                "<li><a target=\"_blank\" href=\"http://mail.sina.com.cn/client/mobile/index.php?suda-key=mail_app&suda-value=login\"  suda-uatrack=\"key=index_new_menu&value=sina_apps_list_click\" style=\"padding-right:12px\">新浪邮箱客户端</a></li>\n" +
                "\n" +
                "                                        </ul>\n" +
                "                                    </div>\n" +
                "                                </div>\n" +
                "                            </div>";

        String regx="http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+";
        Pattern p = Pattern.compile(regx);
        Matcher matcher = p.matcher(str);

        while (matcher.find()){
            String url = matcher.group();
            System.out.println(url);
        }
    }
}
--------------------------
输出:
http://tech.sina.com.cn/z/sinawap/
http://m.weibo.com/web/cellphone.php
http://news.sina.com.cn/m/sinanews.html
http://finance.sina.com.cn/mobile/comfinanceweb.shtml
http://m.sina.com.cn/m/sinasports.shtml
http://edu.sina.com.cn/app/download.shtml
http://licaishi.sina.com.cn/html5/act/ganggu/index.html
http://blog.sina.com.cn/lm/z/app/
http://tianqitong.sina.cn/
http://games.sina.com.cn/o/kb/12392.shtml
http://zhongce.sina.com.cn/about/app
http://mail.sina.com.cn/client/mobile/index.php?suda-key=mail_app&suda-value=login
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值