加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则表达式

发布时间:2020-12-13 23:00:10 所属栏目:百科 来源:网络整理
导读:1、 正则表达式:就是用操作字符串数据的规则表达式。 规则:就是用一些符号组成,每个符号都代表着特有的含义。 其实这些符号相当于对应着底层一段代码。对外提供符号就是简化了操作。 弊端:必须要先学习这些符号。符号多了,阅读性会较差。 span style="f


1、 正则表达式:就是用操作字符串数据的规则表达式。

规则:就是用一些符号组成,每个符号都代表着特有的含义。
其实这些符号相当于对应着底层一段代码。对外提供符号就是简化了操作。

弊端:必须要先学习这些符号。符号多了,阅读性会较差。

<span style="font-size:18px;">	实例演示:
	public class RegexDemo {

		public static void main(String[] args) {

			String QQ = "0123456";
			
			//字符串规则
			String regex = "[1-9][0-9]{4,14}";
			
			//把规则作用于字符串上
			boolean b = QQ.matches(regex);
			System.out.println("QQ" + ":::" + b);
		}
	}</span>

2、 字符范围:[] 字符次数:{}

3、 正则表达式对字符串的常见操作:

1.匹配:
使用的是String类中的matchers方法。

	// 匹配演示,对手机号码进行校验

	public static void checkTel() {
		String str = "15357118217";
		String reg = "[1][358]d{9}";
		boolean b = str.matches(reg);
		System.out.println(b);
	}

2.切割:
注意:split(String s);里面的s是要被正则法则解析的
使用的是String类中的split方法。

	public static void spliDemo() {

		String str = "23  14   56  14 12 -4";
		String[] arr = str.split(" +");
		for (String s : arr)
			System.out.println(s);
	}
----------------------------------------------------------------------------------------
	public static void spliDemo() {
		// 怎么分组:有多少左括号,就有多少组
		String str = "adfddfdfjjjlkj";
		String[] arr = str.split("(.)1+");// 切割叠词,()小括号就是封装,把“.”封装成第一组,1代表的是引用第一组
		for (String s : arr) {
			System.out.println(s);
		}
	}

3.替换:
使用的是String类中的replaceAll方法。

	public static void replaceAllDemo() {
		// String str = "werqqtyuzzzio";
		// str=str.replaceAll("(.)1+","#");
		// 把多个叠词换成一个该叠词
		// str = str.replaceAll("(.)1+","$1");//$1表示引用前一个组的第1组

		String str = "13965739833";
		str=str.replaceFirst("(d{3})d{4}(d{4})","$1****$2");
		System.out.println(str);
	}

4.获取:
将匹配的规则的内容获取出来。

使用正则表达式对象。Pattern
实用步骤:
1. 先将正则表达式编译成Pattern对象。
2. 通过Pattern对象的matcher方法获取Matcher匹配器对象。
3. 通过匹配器对象的方法,将正则规则作用到字符串上以便于操作。

	public static void getDemo() {

		String str = "da jia zhu yi le,yao pai wei dian ying la !";

		String reg = "b[a-z]{3}b";// 三个字母组成的单词取出来。

		// 正则规则被编辑成Pattern对象。
		Pattern p = Pattern.compile(reg);
		// 通过正则对象的方法matcher和字符串关联获取匹配对象。
		Matcher m = p.matcher(str);
		
		//使用匹配器的方法对字符串进行匹配
		while(m.find()){
			System.out.println(m.start()+"---"+m.group()+"---"+m.end());
		}
	}

4、 综合练习,对ip进行排序

	public static void test2() {
		//排序
		String ip="192.108.90.34   10.10.10.10   5.5.5.5   20.132.24.24";
		
		//对字符串补零操作
		ip=ip.replaceAll("(d+)","00$1");
		System.out.println(ip);
		
		ip=ip.replaceAll("0*(d{3})","$1");
		System.out.println(ip);
		
		//把ip切割出来
		String[]ipArr=ip.split(" +");
		//排序
		Arrays.sort(ipArr);
		
		//去掉补的零
		for(String s : ipArr){
			System.out.println(s.replaceAll("0*(d+)","$1"));
		}
	}

5、 网络爬虫:spider 是一段小程序,专门负责获取指定规则数据。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读