正则表达式功能详解

正则表达式的功能:判断功能、分割功能、替换功能。

判断功能:

public boolean matches(String regex):告知此字符串是否匹配给定的正则表达式。
需求1:找出规则,写出正则(1[38][0-9]{9}),校验电话号码
13245678901 13332345678 13456789012 18812345678 18999999999
18666666666 18786868686

public class RegexDemo {
 public static void main(String[] args) {
                String number = "13245678901";
  //正则表达式
  String reg = "1[38][0-9]{9}";
  //调用maches(String reg)进行判断指定字符串是否匹配指定的正则表达式
  boolean flag = number.matches(reg);
  System.out.println(flag);
 }
}

需求2:找出规则,写出正则(String reg = “[a-zA-Z_0-9]+@[a-zA-Z_0-9]{2,8}(\.[comnet]{2,3})+”),校验邮箱
[email protected] [email protected] [email protected] [email protected]
[email protected] [email protected]

public class RegexDemo1 {
 public static void main(String[] args) {
String email = "[email protected]";
  //写一个正则表达式验证这些个邮箱
  String reg = "[a-zA-Z_0-9]+@[a-zA-Z_0-9]{2,8}(\\.[comnet]{2,3})+";
  //依据正则表达式来验证上面的邮箱
  System.out.println(email.matches(reg));
 }
}

分割功能

public String[] split(String regex):根据给定正则表达式的匹配拆分此字符串。
需求1:
分割如下字符串:
String s = “aa,bb,cc”; String rex = " ,";
String s2 = “aa.bb.cc”; String rex = “.”;
String s3 = “aa bb cc”; String rex = " “;
String s4 = “aa bb cc”; String rex = " +”;
String s5 = “D:\baidu\20150826\day14”; String rex = “\\”

需求2:
我有如下一个字符串:”91 27 46 38 50”
请写代码实现最终输出结果是:”27 38 46 50 91”

import java.util.Arrays;
public class RegexDemo5 {
 public static void main(String[] args) {
  //切割字符串
  String s = "91 27 46 38 50";
  String reg = " ";
  String[] strs = s.split(reg);
  //遍历字符串数组,并定义一个int[]
  int[] arr = new int[strs.length];
  for (int i = 0; i < strs.length; i++) {
   arr[i] = Integer.parseInt(strs[i]);
  }
  //排序int[]
  Arrays.sort(arr);//遍历数组
  StringBuffer sb = new StringBuffer();
  for (int i = 0; i < arr.length; i++) {
   sb.append(arr[i]+" ");
  }
  //将sb转换为String类型
  System.out.println(sb.toString());
 }
}

替换功能

public String replaceAll(String regex,String replacement):把符合regex的用replacement替换
需求:字符串中的数字使用*代替。

public class RegexDemo6 {
 public static void main(String[] args) {
  
  String s = "我的银行卡号是:6102333358888";
  String reg = "[0-9]";
  String newStr = s.replaceAll(reg, "*");
  System.out.println(newStr);
 }
}
发布了62 篇原创文章 · 获赞 55 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Veer_c/article/details/103808587