40-正则表达式

正则表达式

  通过一系列分析发现String是一个非常万能的类型,因为String不仅仅可以支持字符串的处理操作,也支持有向各个数据类型的转换支持,所以在项目开发中,只要是用户输入的信息基本上都用String表示。于是再向其他数据类型转换时,为了保证转换的正确性,需要对其进行复杂的验证处理,如果只是单纯的依靠String类中的方法是非常麻烦的。

认识正则表达式

  假设有一个字符串,要求判断是否由数字组成,如果由数字组成,则将其变为数字进行乘法计算。
字符串转数字

public class RegexStudy {
	public static void main(String[] args) {
		String str = "1234";
		if(isNumber(str)) {
			int num = Integer.parseInt(str);
			System.err.println(num *2);
		}
	}
	public static boolean isNumber(String str) {
		char data [] = str.toCharArray();
		for (int x=0; x<data.length; x++) {
			if(data[x] >'9' || data[x]<'0') {
				return false;
			}
		}
		return true;
	}
}

实际上这种验证的功能是非常简单的,但是却需要开发者编写大量的代码实现,在此种情况下,最好使用正则表达式实现;
使用正则表达式实现

public class RegexStudy {
	public static void main(String[] args) {
		String str = "1234";
		if(str.matches("\\d+")) {
			int num = Integer.parseInt(str);
			System.out.println(num * 2);
		}
	}
}

  正则表达式最早是从Perl语言中发展而来的,从JDK1.4之后正则表达式开始被支持,并且提供java.util.regex开发包,同时针对String类也进行了修改使其有方法直接支持正则处理。
  使用正则表达最大的特点在于方便进行验证处理,以及方便进行复杂字符串的修改处理。

常用正则标记(记)

  如果要想进行正则的处理操作,就首先对常用的正则标记进行掌握,从JDK1.4开始提供有java.util.regex开发包提供有Pattern程序类,该类中定义有所有支持的正则标记。

  • 【数量:单个】字符匹配:
    • 任意字符:表示由任意字符组成;
    • \\:匹配“\”;
    • \n:匹配换行;
    • \t:匹配制表符;
  • 【数量:单个】字符集匹配(可以从里面任选一个字符)
    • [abc]:可能是字母abc中任意一个;
    • [^abc]:不是字母abc中的任意一个;
    • [a-zA-Z]:由一个任意字母组成,不区分大小写;
    • [0-9]:表示由一位数字组成;
  • 【数量:单个】简化字符集:
    • .:表示任意一个字符;
    • \d:等价于“[0-9]”;
    • \D:等价于“[^0-9]”;
    • \s:匹配任意的一位空格,可能是空格、换行或制表符;
    • \S:匹配任意一个非空格数据;
    • \w:匹配字母、数字、下划线,等价于“[a-zA-Z_0-9]”;
    • \W:匹配非字母、数字、下划线,等价于“[^a-zA-Z_0-9]”;
  • 边界匹配:
    • ^:匹配边界开始;
    • $:匹配边界开始;
  • 数量表示,默认情况下只有添加上了数量单位才可以匹配多位字符:
    • 表达式?:该正则可以出现0次或1次;
    • 表达式*:该正则可以出现0次或1次或多次;
    • 表达式+:该正则可以出现1次或多次;
    • 表达式{n}:表达式的长度正好为n次;
    • 表达式{n,}:表达式的长度为n次以上;
    • 表达式{n,m}:表达式的长度为n~m次;
  • 逻辑表达式:可以连接多个正则:
    • 表达式X表达式Y:X表达式之后紧跟上Y表达式;
    • 表达式X|表达式Y:有一个表达式满足即可;
    • (表达式X):为表达式X设置一个整体描述,可以为整体描述设置数量单位。

String类对正则的支持

  在进行正则表达式大部分处理的情况下都会基于String类来完成,并且在String提供如下与正则有关的操作方法:

方法名称类型描述
public boolean matches(String regex)普通将指定字符串进行正则判断
public String replaceAll(String regex, String replacement)普通替换全部
public String replaceFirst(String regex, String replacement)普通替换首个
public String[] split(String regex)普通字符串正则拆分
public String[] split(String regex, int limit)普通拆分为指定个数

范例:字符串替换(删除非字母与数字)

public class RegexStudy {

	public static void main(String[] args) {
		String str = "SERTB4W@#$%^56Y43%$^Y3Q4$$5WERFEWG,&^LSDGPSDFG";		//要判断的数据
		String regex = "[^a-zA-Z0-9]+";		//正则表达式
		System.out.println(str.replaceAll(regex, ""));
	}
}

范例:字符串拆分

public class RegexStudy {
	public static void main(String[] args) {
		String str = "a12312312aa23423423n2bnn23n4n23";		//要判断的数据
		String regex = "\\d+";		//正则表达式
		String [] result = str.split(regex);
		for(int x=0; x<result.length; x++) {
			System.out.println(result[x]);
		}
	}
}

在正则处理时对拆分与替换的操作相对容易,但是比较麻烦的是数据验证部分。
范例:判断一个数据是否为小数,若是则将其变为double类型

public class RegexStudy {

	public static void main(String[] args) {
		String str = "100.32";		//要判断的数据
		String regex = "\\d+(\\.\\d+)?";		//正则表达式
		System.out.println(str.matches(regex));
	}
}

范例:判断一个字符串是否由日期组成,若是则将其变为Date类型

import java.text.SimpleDateFormat;

public class RegexStudy {

	public static void main(String[] args) throws Exception {
		String str = "1981-12-12";		//要判断的数据
		String regex = "\\d{4}-\\d{2}-\\d{2}";		//正则表达式
		if(str.matches(regex)) {
			System.out.println(new SimpleDateFormat("yyyy-MM-dd").parse(str));
		};
	}
}

正则表达式无法对内容进行判断,仅能判断格式。
范例:判断给定电话号码是否正确

public class RegexStudy {

	public static void main(String[] args) throws Exception {
		//号码:5799033"\\d{7,8}"
		//04515799033"(\\d{3,4})?\\d{7,8}"
		//(0451)-5799033
		String str = "(0451)-5799033";		//要判断的数据
		String regex = "((\\d{3,4})|(\\(\\d{3,4}\\)-))?\\d{7,8}";		//正则表达式
		System.out.println(str.matches(regex));
	}
}

既然已经可以使用正则进行验证,下面就可以利用其实现一个email地址格式验证。
范例:验证email格式
rre3LT.png

public class RegexStudy {

	public static void main(String[] args) throws Exception {
		//email用户名可以由字母、数字、_所组成(不应使用_开头)
		//email域名可以由字母、数字、_、-所组成
		//email后缀为.cn、.com、.net、.com.cn、.gov
		String str = "mldnjava888@mldn.com.cn";		//要判断的数据
		String regex = "[a-zA-Z0-9]\\w+@\\w+\\.(cn|com|nwt|gov|com\\.cn)";		//正则表达式
		System.out.println(str.matches(regex));
	}
}

  现在这几种正则匹配处理操作是最常见的过程。

java.util.regex包支持

  虽然大部分情况下都可以使用String类实现正则的操作,但是也有一些情况下需要使用java.util.regex开发包中提供的正则处理类。该类中提供两个类:正则表达式编译类:Pattern;正则匹配类:Matcher;

  • Pattern类提供有正则表达式的编译处理支持:public static Pattern compile(String regex);
    • 同时提供字符串拆分支持:public String[] split(CharSequence input);
import java.util.regex.Pattern;

public class RegexStudy {

	public static void main(String[] args) throws Exception {
		String str = "adsgsdfg()2#$%^dfgh#%^DFh2345DFH@$#";		//要判断的数据
		String regex = "[^a-zA-Z0-9]+";		//正则表达式
		Pattern pat = Pattern.compile(regex);
		String reslut[] = pat.split(str);
		for(int x=0;x<reslut.length;x++) {
			System.out.println(reslut[x]);
		}
	}
}
  • Matcher类:实现正则匹配的处理类,这个类的对象实例化依靠Pattern类完成:
    • Pattern提供的方法:public Matcher matcher(CharSequence input);
    • 当获取了Matcher类对象之后就可以利用该类中的方法进行如下操作:
      • 正则匹配:public boolean matches();
      • 正则替换:public String replaceAll(String replacement);
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexStudy {

	public static void main(String[] args) throws Exception {
		String str = "101";		//要判断的数据
		String regex = "\\d+";		//正则表达式
		Pattern pat = Pattern.compile(regex);
		Matcher mat = pat.matcher(str);
		System.out.println(mat.matches());
	}
}

  如果纯粹的是以拆分、替换、匹配三种操作为例根本用不到java.utiol.regex开发包,只依靠String类就可以实现了。但是Matcher类中提供有一种分组的功能,而这种分组的功能是String不具备的。

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexStudy {

	public static void main(String[] args) throws Exception {
		//要求取出“#{内容}”标记中的所有内容
		String str = "INSERT INTO dept(deptno,dname,loc) VALUES (#{deptno},#{dname},#{loc})";	//要判断的数据
		String regex = "#\\{\\w+\\}";		//正则表达式
		Pattern pat = Pattern.compile(regex);
		Matcher mat = pat.matcher(str);
		while(mat.find()) {		//是否有匹配成功的内容
			System.out.println(mat.group(0).replaceAll("#|\\{|\\}", ""));
		}
	}
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值