正则表达式基础2

注释:正则表达式的学习记录2

常见表达式

​ boolean: matches(String regex),称为匹配字符串,其中regex是正则的规则,表达式返回boolean类型值告知此字符串是否匹配给定的正则表达式。用法例如,"abc".matches("[a]") 匹配成功返回true

​ String[]: split(String regex),称为切割字符串,其中regex是正则的规则,根据给定正则表达式的匹配拆分此字符串。

​ String: replaceALL(String regex,String replacement),称为替换字符串,其中regex是正则的规则,使用给定的replacement替换此字符串所有匹配给定的正则表达式的子字符串。

几个例子

例1.校验手机号码,要求:

1、要求为11位数字
2、要求第一位为1,第二位为3、4、5、7、8中的一个,后面9位为0到9之间的任意数字。
代码演示
public static void main(String[] args) {
    checkphone();
}
/*
 * 本函数用于检查手机号码是否合法,具体实现:
 * 1.11位数字;2.要求第一位为1,第二位为3、4、5、7、8中的一个,后面9位为0到9之间的任意数字。
 */
 public static void checkphone(){
     Scanner input = new Scanner(System.in);
     System.out.println("请输入手机号:");
     String phone = input.next();
     String regex = "1[34578][0-9]{9}";
     //检查手机号码和规则是否匹配,String类的方法matches
     boolean b = phone.matches(regex);
     //当输出的布尔型为true时,表示所输入的手机号正确,反之输入错误
     System.out.println(b);
     if(b==true){
         System.out.print("手机号码输入正确!");
     }else{
         System.out.print("手机号码输入错误!");
     }
 }
}
输出结果

结果1请输入手机号:12345678false手机号码输入错误! 结果2请输入手机号:18677456879true手机号码输入正确!

例2.分割出字符串中的数字,从字符串"18-46-21-73"中提取出数字

代码演示
import java.util.Arrays;
//通过正则拆分函数从字符串中拆分出数字
public class RegexDemo2 {
   public static void main(String[] args) {
       String sc = "18-46-21-73";   //给定原字符串
       String regex = "-";   //拆分正则规则
       String[] fc = sc.split(regex);   //拆分结果
       System.out.print(Arrays.toString(fc));   //打印输出结果
   }
}
输出结果

[18, 46, 21, 73]

例3.把文字中的数字替换成%,将所给的字符串"Welcome743 42the4 World887!"中的数字替换成%

代码演示
//将所给的字符串中的数字替换成%
public class RegexDemo3 {
   public static void main(String[] args) {
       String sc ="Welcome743 42the4 World887!";   //给定原字符串
       String regex = "[0-9]";   //替换规则
       String result = sc.replaceAll(regex, "%");    //替换
       System.out.print(result);    //打印输出结果
   }
}
输出结果

Welcome%%% %%the% World%%%!

例4.匹配正确的数字

匹配规则:(不考虑0)
匹配正整数:”\\d+
匹配正小数:”\\d+\\.\\d+  
匹配负整数:”-\\d+
匹配负小数:”-\\d+\\.\\d+
匹配保留两位小数的正数:”\\d+\\.\\d{2}
匹配保留1-3位小数的正数:”\\d+\\.\\d{1,3}
程序实例
import java.util.Scanner;
public class RegexDemo4 {
    /**
     根据要求匹配数字
     */
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("请输入一个正整数:");
        String number1 = input.next();   //输入一个数字
        String regex = "\\d+";   //匹配正则规则
        boolean b = number1.matches(regex);  //匹配数字
        System.out.println(b);    //打印结果,true则符合要求
    }
}
输出结果

请输入一个正整数:39true

例5.获取IP地址:匹配规则 ”\.”

程序实例
import java.util.Arrays;
public class RegexDemo5 {
    /**
     *获取IP地址(192.168.1.100)中的每段数字
     */
    public static void main(String[] args) {
        String sc = "192.168.1.100";   //给定原字符串
        String regex = "\\.";   //拆分正则规则
        String[] fc = sc.split(regex);   //拆分结果
        System.out.print(Arrays.toString(fc));   //打印输出结果
    }
}
输出结果

[192, 168, 1, 100]

猜你喜欢

转载自blog.csdn.net/daimaxiaoxin/article/details/79995831