正则表达式
场景导入
- 要求:判断一个字符串是否全部由数字组成。
实现原理:将字符串变为字符数组,而后判断每个字符是否在0-9
之间。
范例:判断字符串是否全部由数字组成
public class Demo {
public static void main(String[] args) throws Exception {
String str = "1234";
System.out.println(isNumber(str));
}
public static boolean isNumber(String temp) {
char data[] = temp.toCharArray(); // 将字符串变为字符数组,目的是循环取出
for (int x = 0; x < data.length; x++) {
if (data[x] > '9' || data[x] < '0') {
return false;
}
}
return true;
}
}
判断字符串是否由数字组成,是一个很简单的功能,但上述代码却需要8行代码实现。如果是更复杂的判断,那就需要更多的代码,下面进行简化:
public class Demo {
public static void main(String[] args) throws Exception {
String str = "1234";
System.out.println(str.matches("\\d+")); // 使用正则表达式
}
}
java.util.regex
- JDK1.4才正式引入正则表达式的工具类,所有的正则表达式工具类都定义在
java.util.regex
包中。在JDK1.4之前,需要单独下载一个正则表达式的开发包才能使用。 - java.util.regex包中定义了两个主要的类:
- Pattern类:用于编译正则表达式,获取该类对象只能通过compile()。
- Matcher类:该类对象通过Pattern类取得,用于匹配
正则标记
正则表达式的的所有标记都在java.util.regex.Pattern类中定义。
- 单个字符
字符
: 匹配单个字符;\\
:表示转义字符“\”;\t
:匹配“\t”符号\n
:匹配换行(\n)符号
public class Demo {
public static void main(String[] args) throws Exception {
String str = "tt";
// 判断字符内容是否符合你要的
System.out.println(str.matches("tt")); // true
System.out.println(str.matches("t")); // false
System.out.println(str.matches("TT")); // false
// 表示转义字符“\”
String strA = "t\\";
System.out.println(strA); // t\
// 匹配制表符
String strB = "\t";
System.out.println(strB.matches("\t")); // true
// 匹配换行符号
String strC = "\n";
System.out.println(strC.matches("\n")); // true
}
}
- 字符集
[abc]
:匹配值为a或b或c的字符[^abc]
:匹配值为非a,非b,非c的字符;[a-z]
:匹配所有的小写英文字符;[a-zA-Z]
:匹配所有的英文字符,不区分大小写;
public class Demo {
public static void main(String[] args) throws Exception {
// 数量为1,即只能进行单个字符判定
String str = "t";
String strA = "a";
String strB = "9";
System.out.println(str.matches("[abc]")); // false
System.out.println(strA.matches("[abcd]")); // true
System.out.println(str.matches("[^abc]")); // true
System.out.println(str.matches("[a-z]")); // true
System.out.println(str.matches("[A-Z]")); // false
System.out.println(str.matches("[a-zA-Z]")); // true
System.out.println(strB.matches("[0-9]")); // true
}
}
- 简化字符集
.
:匹配任意字符;\d
:匹配0-9之间的任意数字,等价于[0-9]
;\D
:等价于[^0-9]
;\s
: 匹配任意的空白字符,如\t
,\n
;\S
:匹配任意的非空白字符;\w
:等价于[a-zA-Z_0-9]
,匹配英文字母、数字、下划线;\w
:等价于[^a-zA-Z_0-9]
,匹配不是英文字母,不是数字,不是下划线的内容;
public class Demo {
public static void main(String[] args) throws Exception {
// 数量为1,即只能进行单个字符判定
String str = "\t";
String strA = "a";
String strB = "9";
System.out.println(str.matches(".")); // true
System.out.println(str.matches("\\s")); // true
System.out.println(str.matches("\\D")); // true
System.out.println(strA.matches("\\S")); // true
System.out.println(strA.matches("\\w")); // true
System.out.println(strA.matches("\\W")); // false
System.out.println(strB.matches("\\d")); // true
}
}
- 边界匹配(不要在Java中使用,在JavaScript使用)
^
:正则的开始;$
:正则的结束。
- 数量表达
正则条件?
:表示此正则条件可以出现1次或0次;正则条件+
:表示此正则条件可以出现1次或1次以上;正则条件*
:表示此正则可以出现0次或0次以上;正则条件{n}
:表示此正则条件只能出现n次;正则条件{n,}
:表示此正则只能出现n次或n次以上正则条件{n,m}
:表示此正则只能出现n~m次
public class Demo {
public static void main(String[] args) throws Exception {
// 数量为1,即只能进行单个字符判定
String str = "";
String strA = "1";
String strB = "12";
// \\d?表示数字可以出现1次或0次,超过即为false
System.out.println(str.matches("\\d?")); // true
System.out.println(strA.matches("\\d?")); // true
System.out.println(strB.matches("\\d?")); // false
// \\d+表示数字可以出现1次或1次以上,0次为false
System.out.println(str.matches("\\d+")); // false
System.out.println(strB.matches("\\d+")); // true
// \\d*表示数字可以出现0次或0次以上
System.out.println(str.matches("\\d*")); // true
System.out.println(strA.matches("\\d*")); // true
System.out.println(strB.matches("\\d*")); // true
// \\d{2}表示数字只能出现2次,高于或低于都是false
System.out.println(strB.matches("\\d{2}")); // true
System.out.println(strA.matches("\\d{2}")); // false
// \\d{1,}表示数字只能出现1次或1次以上
System.out.println(strB.matches("\\d{1,}")); // true
System.out.println(strA.matches("\\d{1,}")); // true
// \\w{3,5}表示数字、字母和_只能出现3~5次
String strC = "admin";
String strD = "ad";
String strE = "superadmin";
System.out.println(strC.matches("\\w{3,5}")); // true
System.out.println(strD.matches("\\w{3,5}")); // false
System.out.println(strE.matches("\\w{3,5}")); // false
}
}
- 逻辑运算
- 正则条件1 正则条件2:要同时符合正则条件1和正则条件2;
- 正则1 | 正则2:正则条件1或者正则条件2,有一组满足即可;
- (正则):将多个正则绑定为一组,为该组设置出现的次数。
String类对正则的支持
在JDK1.4之后,由于正则表达式的引入,String类中也增加了相应的操作方法。
No. | 方法名称 | 类型 | 功能 |
---|---|---|---|
1 | public boolean matches(String regex) | 普通 | 正则验证,使用指定的字符串判断其是否符合正则表达式 |
2 | public String replaceAll (String regex, String replacement) | 普通 | 全部替换 |
3 | public String replaceFirst (String regex, String replacement) | 普通 | 替换首个符合条件的字符串 |
4 | public String[] split(String regex) | 普通 | 全部拆分 |
5 | public String[] split(String regex,int limit) | 普通 | 部分拆分 |
范例:字符串替换
public class Demo {
public static void main(String[] args) throws Exception {
String str = "wokunJL*)(*()klj4e32u798FJI&(*#RHLKEWSF(*";
// 保留小写字母,即把所有不是小写字母的替换为""
String regex = "[^a-z]"; // 此处编写正则表达式
System.out.println(str.replaceAll(regex,""));
}
}
范例:字符串拆分
public class Demo {
public static void main(String[] args) throws Exception {
String str = "kj8LK89ssL8798KLLKlkllk5555ww";
// 按照数字拆分
String regex = "\\d+"; // 此处编写正则表达式
String result[] = str.split(regex);
for (int x = 0; x < result.length; x++) {
System.out.println(result[x]);
}
}
}
范例:验证一个字符串是否是数字,如果是则将其变为double型;数字可能是整数也可能是小数;
public class Demo {
public static void main(String[] args) throws Exception {
String str = "10";
String strA = "10.1";
String strB = "10.";
String regex = "\\d+(\\.\\d+)?";
System.out.println(str.matches(regex));
System.out.println(strA.matches(regex));
System.out.println(strB.matches(regex));
if (strA.matches(regex)) { // 转型前进行验证
System.out.println(Double.parseDouble(strA));
}
}
}
范例:判断字符串是否是IP地址(IPv4)
public class Demo {
public static void main(String[] args) throws Exception {
String str = "192.168.1.1";
String regex = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";
System.out.println(str.matches(regex));
}
}
范例:简化判断字符串是否是IP地址
public class Demo {
public static void main(String[] args) throws Exception {
String str = "192.168.1.1";
String regex = "(\\d{1,3}\\.){3}\\d{1,3}";
System.out.println(str.matches(regex));
}
}
范例:判断字符串是否是日期格式,如果是则转换为Date型数据
public class Demo {
public static void main(String[] args) throws Exception {
String str = "2017-05-03";
String regex = "\\d{4}-\\d{2}-\\d{2}";
System.out.println(str.matches(regex));
if (str.matches(regex)) {
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(str);
System.out.println(date);
}
}
}
范例:判断电话号码,以下格式都行:
- 格式1:51283346,一般长度是7~8位(\d{7,8});
- 格式2:010-51283346,区号一般是3~4位,“-”只有区号出现时才出现((\d{3,4}-)?\d{7,8})
- 格式3:(010)-51283346(((\d{3,4}-)|(\(\d{3,4}\)-))?\d{7,8})
public class Demo {
public static void main(String[] args) throws Exception {
String str = "(010)-51283346";
String regex = "((\\d{3,4}-)|(\\(\\d{3,4}\\)-))?\\d{7,8}";
System.out.println(str.matches(regex)); // true
}
}
范例:验证email地址
- 要求格式一:email由字母、数字、_组成;思路图如下:
public class Demo {
public static void main(String[] args) throws Exception {
String str = "hello_nihao123@mldn.cn";
String regex = "\\w+@\\w+\\.\\w+";
System.out.println(str.matches(regex)); // true
}
}
- 要求格式二:用户名(由字母、数字、_组成,必须以字母开头,以字母或数字结尾,用户名长度不超过30,最后的根域名只是.com、.cn、.net、.com.cn、.net.cn、.edu、.gov、.org,思路图如下:
public class Demo {
public static void main(String[] args) throws Exception {
String str = "hello.nihao123_123@mldn.c";
String regex = "[a-zA-Z][a-zA-Z0-9_\\.]{0,28}[a-zA-Z0-9]@\\w+\\." +
"(com|net|cn|com\\.cn|net\\.cn|org|gov|edu)";
System.out.println(str.matches(regex)); // true
}
}
- 开发中大多数正则匹配都是由String类完成。而正则最开始的开发包是java.util.regex,这个包提供有两个类。
范例:Pattern类
public class Demo {
public static void main(String[] args) throws Exception {
String str = "a1b22c333d4444e55555f";
String regex = "\\d+";
Pattern pattern = Pattern.compile(regex); // 编译正则表达式
String result[] = pattern.split(str); // 拆分字符串
System.out.println(Arrays.toString(result));
}
}
范例:字符串验证
public class Demo {
public static void main(String[] args) throws Exception {
String str = "3223231";
String regex = "\\d+";
Pattern pattern = Pattern.compile(regex); // 编译正则表达式
Matcher mat = pattern.matcher(str); // 进行正则匹配
System.out.println(mat.matches());
}
}
由于String类本身支持上述两个操作,因此很少使用java.util.regex中的Pattern与Matcher类。