正则表达式..

news2024/9/22 9:46:57

1.字符串的合法检验

现在有一个字符串验证码 我们需要检验其的合法性 什么条件才能够使得字符串合法呢?就是6-10个字符串长度 并且以字母开头 并且其中由字母、数字、下划线构成
那么我们可以先通过自定义的方式进行检验

public class Main {
    public static void main(String[] args) {
        System.out.println(validate("aaaaaa"));
    }
    private static boolean validate(String email){
        // 如果参数为空的话 那么说明不合法 提醒一下并且返回false
        if(email == null){
            System.out.println("邮箱不能为空");
            return false;
        }
        // 由于之后获取参数字符串中的字符方法charAt()开头需要对字符串进行长度判断 如果多次调用的话 时间方面的效率肯定很低 但是好在他是在原先字符串的基础上进行获取的 所以我们利用空间换时间的方法 拷贝一个字符串的内存 优化了时间 但多开辟了空间
        char[] chs = email.toCharArray();
        int len = chs.length;
        // 如果参数的长度不合要求的话 那么提醒一下并且返回false 由于长度需要多次获取 所以提前定义一个变量 用于保存这个参数的长度
        if(len < 6 || len > 10){
            System.out.println("长度不合法");
            return false;
        }
        // 是否以字母开头
        if(!isLetter(chs[0])){
            System.out.println("不是以字母开头");
            return false;
        }
        // 是否由字母、数字、下划线构成
        for(int i = 1; i < len; ++i){
            // 获取当前遍历的字符
            char ch = chs[i];
            if(isLetter(ch) || isDigit(ch) || ch == '_')continue;
            return false;
        }
        // 如果上述判断都没有返回false的话 那么说明这个邮箱字符串是合法的
        return true;
    }
    private static boolean isLetter(char ch){
        if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))return true;
        return false;
    }
    private static boolean isDigit(char ch){
        if(ch >= '0' && ch <= '9')return true;
        return false;
    }
}

但是我们可以看到其实我们自己自定义的方法写的很繁杂 所以我们可以引入正则表达式来替代复杂的验证逻辑

public class Main {
    public static void main(String[] args) {
        String regex = "[a-zA-Z][a-zA-Z0-9_]{5,9}";
        System.out.println("aaaaaa".matches(regex));
    }
}
public class Main {
    public static void main(String[] args) {
        String regex = "[a-zA-Z]\\w{5,9}";
        System.out.println("aaaaa".matches(regex));
    }
}

2.单字符匹配

1.[bcr]–可以匹配括号内的任意一个字符

public class Main {
    public static void main(String[] args) {
        // 等价于[b|c|r]或者(b|c|r) 但是一般写成[bcr]比较简练一点 推荐使用[bcr]写法
        String regex = "[bcr]at";
        System.out.println("bat".matches(regex));// true
        System.out.println("cat".matches(regex));// true
        System.out.println("rat".matches(regex));// true
        System.out.println("hat".matches(regex));// false
    }
}

2.[ ^bcr ]–可以匹配除了括号内以外的任意一个字符

public class Main {
    public static void main(String[] args) {
        String regex = "[^bcr]";
        System.out.println("bat".matches(regex));// false
        System.out.println("cat".matches(regex));// false
        System.out.println("rat".matches(regex));// false
        System.out.println("hat".matches(regex));// true
    }
}

3.[1-5]–可以匹配括号内指定范围内的任意一个字符

public class Main {
    public static void main(String[] args) {
        String regex = "foo[1-5]";
        System.out.println("foo1".matches(regex));// true
        System.out.println("foo2".matches(regex));// true
        System.out.println("foo3".matches(regex));// true
        System.out.println("foo4".matches(regex));// true
        System.out.println("foo5".matches(regex));// true
        System.out.println("foo6".matches(regex));// false
    }
}

4.[ ^1-5 ]–可以匹配括号指定范围以外的任意一个字符

public class Main {
    public static void main(String[] args) {
        String regex = "foo[^1-5]";
        System.out.println("fook".matches(regex));// true
        System.out.println("foo6".matches(regex));// true
        System.out.println("foo5".matches(regex));// false
    }
}
public class Main {
    public static void main(String[] args) {
        String regex = "foo1-5";
        System.out.println("foo6".matches(regex));// false
        System.out.println("foo5".matches(regex));// false
        System.out.println("foo1-5".matches(regex));// true
    }
}

5.[0-46-8]或者[0-4[6-8]]–匹配两个范围的并集部分的任意一个字符

public class Main {
    public static void main(String[] args) {
        String regex = "[0-46-8]";
        System.out.println("4".matches(regex));// true
        System.out.println("5".matches(regex));// false
    }
}
public class Main {
    public static void main(String[] args) {
        String regex = "[0-4[6-8]]";
        System.out.println("4".matches(regex));// true
        System.out.println("5".matches(regex));// false
    }
}

6.[a-z&&[def]]–匹配两个范围的交集部分的任意一个字符

public class Main {
    public static void main(String[] args) {
        // 也可以写成[a-z&&[def]]
        String regex = "[a-z&&def]";
        System.out.println("d".matches(regex));// true
        System.out.println("e".matches(regex));// true
        System.out.println("f".matches(regex));// true
        System.out.println("o".matches(regex));// false
    }
}

7.[a-z&&[ ^bc ]]–匹配两个范围的差集部分的任意一个字符 即前面范围和后面范围的差集(就是属于前面范围但是不属于后面范围的任意一个字符 相当于[ad-z])

public class Main {
    public static void main(String[] args) {
        String regex = "[a-z&&[^bc]]";
        System.out.println("a".matches(regex));// true
        System.out.println("b".matches(regex));// true
        System.out.println("c".matches(regex));// false
        System.out.println("d".matches(regex));// true
    }
}

3.预定义字符

在正则表达式中 其实已经存在了许多提前定义好的字符:
. – 匹配任意一个字符
\d – 匹配数字中的任意一个字符(等价于[0-9])
\D – 匹配非数字中的任意一个字符(等价于[ ^0-9 ])
\s – 匹配空白字符中的任意一个字符(等价于[ \t\n\f\r] 注意前面有一个空格 因为空格也属于空白字符)
\S – 匹配非空白字符中的任意一个字符(等价于[ ^\s ])
\w – 匹配单词字符中的任意一个字符(单词字符包括数字、字母、下划线 等价于[a-zA-Z0-9])
\W – 匹配非单词字符中的任意一个字符(等价于[ ^\w ])

public class Main {
    public static void main(String[] args) {
        String regex = ".";
        System.out.println("123".matches(regex));// false
        System.out.println("1".matches(regex));// true
    }
}
public class Main {
    public static void main(String[] args) {
        // 我们都知道.可以匹配任意一个字符 但是其实有一种用法只能匹配.这个字符 就是\\.
        String regex = "\\.";
        System.out.println(".".matches(regex));// true
        System.out.println("1".matches(regex));// false
    }
}

相当于123位置处必须填写123 而不是任意从中取出一个字符来 而[和]位置处也必须写上[和]才行

public class Main {
    public static void main(String[] args) {
        // 其实不止是\\.有匹配仅有的.的作用 \\[ \\]也有类似的作用
        String regex = "\\[123\\]";
        System.out.println("1".matches(regex));// false
        System.out.println("[1]".matches(regex));// false
        System.out.println("[123]".matches(regex));// true
    }
}

需要注意的是由于Java中存在转义字符 所以\和诸如t这样的字符组合会将t转义为其他的字符 要在最前面在加上一个\ 即\t

public class Main {
    public static void main(String[] args) {
        String regex = "\\d";
        System.out.println("1".matches(regex));// true
        System.out.println("a".matches(regex));// false
        System.out.println("12".matches(regex));// false
    }
}
public class Main {
    public static void main(String[] args) {
        String regex = "\\D";
        System.out.println("1".matches(regex));// false
        System.out.println("a".matches(regex));// true
        System.out.println("ab".matches(regex));// false
    }
}
public class Main {
    public static void main(String[] args) {
        String regex = "\\s";
        System.out.println(" ".matches(regex));// true
        System.out.println("\t".matches(regex));// true
        System.out.println("\n".matches(regex));// true
        System.out.println("\f".matches(regex));// true
        System.out.println("\r".matches(regex));// true
        System.out.println("a".matches(regex));// false
    }
}
public class Main {
    public static void main(String[] args) {
        String regex = "\\S";
        System.out.println(" ".matches(regex));// false
        System.out.println("\t".matches(regex));// false
        System.out.println("\n".matches(regex));// false
        System.out.println("\f".matches(regex));// false
        System.out.println("\r".matches(regex));// false
        System.out.println("a".matches(regex));// true
    }
}
public class Main {
    public static void main(String[] args) {
        // 单词只包括数字、字母、下划线
        String regex = "\\w";
        System.out.println("1".matches(regex));// true
        System.out.println("a".matches(regex));// true
        System.out.println("_".matches(regex));// true
        System.out.println("#".matches(regex));// false
    }
}
public class Main {
    public static void main(String[] args) {
        // 单词只包括数字、字母、下划线
        String regex = "\\W";
        System.out.println("1".matches(regex));// false
        System.out.println("a".matches(regex));// false
        System.out.println("_".matches(regex));// false
        System.out.println("#".matches(regex));// true
    }
}

4.量词

在这里插入图片描述

public class Main {
    public static void main(String[] args) {
        // x{n} 说明x出现了n次
        String regex = "6{3}";
        System.out.println("66".matches(regex));// false
        System.out.println("666".matches(regex));// true
        System.out.println("6666".matches(regex));// false
    }
}
public class Main {
    public static void main(String[] args) {
        // x{n, m} 说明x出现了指定范围内的任意一个次数
        String regex = "6{2,4}";
        System.out.println("6".matches(regex));// false
        System.out.println("66".matches(regex));// true
        System.out.println("666".matches(regex));// true
        System.out.println("6666".matches(regex));// true
        System.out.println("66666".matches(regex));// false
    }
}
public class Main {
    public static void main(String[] args) {
        // x{n, m} 说明x至少出现了n次
        String regex = "6{2,}";
        System.out.println("6".matches(regex));// false
        System.out.println("66".matches(regex));// true
        System.out.println("666".matches(regex));// true
        System.out.println("6666".matches(regex));// true
        System.out.println("66666".matches(regex));// true
    }
}
public class Main {
    public static void main(String[] args) {
        // x? 说明x出现了0次或者1次
        String regex = "6?";
        System.out.println("".matches(regex));// true
        System.out.println("6".matches(regex));// true
        System.out.println("66".matches(regex));// false
    }
}
public class Main {
    public static void main(String[] args) {
        // x* 说明x至少出现了0次
        String regex = "6*";
        System.out.println("".matches(regex));// true
        System.out.println("6".matches(regex));// true
        System.out.println("66".matches(regex));// true
    }
}
public class Main {
    public static void main(String[] args) {
        // x+ 说明x至少出现了1次
        String regex = "6+";
        System.out.println("".matches(regex));// false
        System.out.println("6".matches(regex));// true
        System.out.println("66".matches(regex));// true
    }
}

5.Pattern和Matcher

其实我们所使用的String类中的match方法底层使用到了Pattern和Matcher两个类
在这里插入图片描述
第一行是检查我们所写的正则表达式语法是否正确 第二行则是对两者进行匹配 第三行则是返回匹配结果

其实Matcher不止有matches方法 还有其他常用的方法

1.find方法

该方法属于部分匹配 即查看是否包含符合条件的子串 而matches则属于完全匹配
并且和while循环搭配使用的话 就可以查找指定字符串中的所有符合条件的子串 直到找不到为止

public class Main {
    public static void main(String[] args) {
        // match方法是完全匹配 而find方法则是部分匹配 也就是查看正则表达式中是否包含字符串
        // 检查正则表达式是否合法
        Pattern p = Pattern.compile("\\d{3}");
        // 然后将正则表达式和字符串进行匹配
        Matcher m = p.matcher("123_456_789");
        // 然后打印匹配结果
        System.out.println(m.find());
    }
}

2.find、group、start、end方法

以下这个案例可以找到指定字符串中符合正则表达式的所有子串 并且打印他的内容以及他的开始索引以及结束索引信息
一般如果你不使用这个flags的话 那么直接传递一个0即可

public class Main {
    public static void main(String[] args) {
        String input = "123_456_789_101_112";
        String regex = "\\d{3}";
        findAll(regex, input);
    }
    // 定义一个方法 用于查找所有符合条件的子串
    public static void findAll(String regex, String input){
        findAll(regex, input, 0);
    }
    // 定义一个方法 用于查找所有符合条件的子串
    public static void findAll(String regex, String input, int flags){
        // 如果正则表达式为空或者字符串为空的话 那么就执行下面操作
        if(regex == null || input == null)return;
        // 首先我们先检查合法的正则表达式
        Pattern p = Pattern.compile(regex, flags);
        // 然后定义一个匹配器 参数为两个参与匹配的字符串
        Matcher m = p.matcher(input);
        // 定义一个变量 用于查看是否存在符合条件的子串
        boolean found = false;
        // 然后遍历每一个符合条件的子串 并且获取每一个子串的内容以及开始和结束索引 注意是[开始索引, 结束索引)
        while(m.find()){
        	found = true;
            System.out.print("\"" + m.group() + "\", ");
            System.out.println("[" + m.start() + ", " + m.end() + "]");
        }
        // 如果不存在符合条件的子串 那么就打印不存在符合条件的子串
        if(!found){
			System.out.println("no match.");
		}
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1398347.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

通过Konva.js实现canvas列表滚动

列表可以通过Konva.js中的Rect来实现&#xff0c;通过group可以丰富列表的内容 在滚动方面&#xff0c;可以通过vue的scroll方法&#xff0c;通过rect中的move方法来修改y值即可 我这里设置的是一个透明的盒子在想要滚动的canvas上&#xff0c;这样就可以实现直接滚动canvas列…

K8s(七)四层代理Service

Service概述 Service在Kubernetes中提供了一种抽象的方式来公开应用程序的网络访问&#xff0c;并提供了负载均衡和服务发现等功能&#xff0c;使得应用程序在集群内外都能够可靠地进行访问。 每个Service都会自动关联一个对应的Endpoint。当创建一个Service时&#xff0c;Ku…

springboot109新闻稿件管理系统

简介 【毕设源码推荐 javaweb 项目】基于springbootvue 的新闻稿件管理系统 适用于计算机类毕业设计&#xff0c;课程设计参考与学习用途。仅供学习参考&#xff0c; 不得用于商业或者非法用途&#xff0c;否则&#xff0c;一切后果请用户自负。 看运行截图看 第五章 第四章 获…

SpringMVC下半篇之整合ssm

4.ssm整合 4.1.创建表 CREATE TABLE account (id int(11) NOT NULL AUTO_INCREMENT,name varchar(20) DEFAULT NULL,money double DEFAULT NULL,PRIMARY KEY (id) ) ENGINEInnoDB DEFAULT CHARSETutf8;4.2.创建工程 4.3.pom.xml <?xml version"1.0" encoding&…

【图形学】颜色线性插值和Wu反走样算法

颜色线性插值 绘制一条颜色渐变的直线&#xff0c;直线上每一个点的颜色都来自端点颜色的线性插值。线性插值公式为 P ( 1 − t ) P s t a r t t P e n d P 是直线上任意一个点&#xff0c; P s t a r t 是直线的起点&#xff0c; P e n d 是直线的终点 对应直线上任意一点…

[flutter]GIF速度极快问题的两种解决方法

原因&#xff1a; 当GIF图没有设置播放间隔时间时&#xff0c;电脑上会默认间隔0.1s&#xff0c;而flutter默认0s。 解决方法一&#xff1a; 将图片改为webp格式。 解决方法二&#xff1a; 为图片设置帧频率&#xff0c;添加播放间隔。例如可以使用GIF依赖组件设置每秒运行…

低代码技术杂谈

一、探讨低代码的定义 “Low-Code”是什么&#xff1f;身为技术人员听到这种技术名词&#xff0c;咱们第一反应就是翻看维基百科 或者其他相关技术论文&#xff0c;咱们想看维基百科的英文介绍&#xff1a; A low-code development platform (LCDP) provides a development env…

Docker(七)使用网络

作者主页&#xff1a; 正函数的个人主页 文章收录专栏&#xff1a; Docker 欢迎大家点赞 &#x1f44d; 收藏 ⭐ 加关注哦&#xff01; Docker 中的网络功能介绍 Docker 允许通过外部访问容器或容器互联的方式来提供网络服务。 一、外部访问容器 容器中可以运行一些网络应用&…

数学建模常见算法的通俗理解(1)

目录 1.层次分析法&#xff08;结合某些属性及个人倾向&#xff0c;做出某种决定&#xff09; 1.1 粗浅理解 1.2 算法过程 1.2.1 构造判断矩阵 1.2.2 计算权重向量 1.2.3 计算最大特征根 1.2.4 计算C.I.值 1.2.5 求解C.R.值 1.2.6 判断一致性 1.2.7 计算总得分 2 神经…

go语言(八)---- map

map的声明方式有以下三种。 package mainimport "fmt"func main() {//第一种声明方式//声明map1是一个map类型&#xff0c;key是String&#xff0c;value是Stringvar myMap1 map[string] stringif myMap1 nil {fmt.Println("myMap1 是一个空map")}//在使…

多测师肖sir___ui自动化测试po框架(升级)

ui自动化测试po框架&#xff08;升级&#xff09; po框架 一、ui自动化po框架介绍 &#xff08;1&#xff09;PO是Page Object的缩写&#xff08;pom模型&#xff09; &#xff08;2&#xff09;业务流程与页面元素操作分离的模式&#xff0c;可以简单理解为每个页面下面都有一…

java数据结构与算法刷题-----LeetCode59. 螺旋矩阵 II

java数据结构与算法刷题目录&#xff08;剑指Offer、LeetCode、ACM&#xff09;-----主目录-----持续更新(进不去说明我没写完)&#xff1a;https://blog.csdn.net/grd_java/article/details/123063846 解题思路 初始&#xff0c;top行执向第一行&#xff0c;bottom行指向最后一…

积分梳状滤波器CIC原理与实现

CIC&#xff08;Cascade Intergrator Comb&#xff09;&#xff1a;级联积分梳状滤波器&#xff0c;是由积分器和梳状滤波器级联而得。滤波器系数为1&#xff0c;无需对系数进行存储&#xff0c;只有加法器、积分器和寄存器&#xff0c;资源消耗少&#xff0c;运算速率高&#…

TypeScript语法总结

JavaScript 与 TypeScript 的区别 TypeScript 是 JavaScript 的超集&#xff0c;扩展了 JavaScript 的语法&#xff0c;因此现有的 JavaScript 代码可与 TypeScript 一起工作无需任何修改&#xff0c;TypeScript 通过类型注解提供编译时的静态类型检查。 TypeScript 可处理已…

GitHub 13.7k star,一款让Windows和macOS瘦身减肥实用工具,免安装+开源+性能高

GitHub 13.7k star&#xff0c;一款让Windows和macOS瘦身减肥实用工具&#xff0c;免安装开源性能高 大家好&#xff01;我是老码农。 今天给大家推荐一款&#xff1a;让Windows和macOS操作系统瘦身减肥的实用工具&#xff0c;czkawka。 这款工具主要干啥事呢&#xff1f;说…

Latex绘图

排查Latex报错 “Command \csubfigure already defined” 这个可以通过添加如下命令&#xff1a; \usepackage{subfig} \usepackage{subfloat} ..... \begin{figure*}[h] \centering \subfloat[subfloat title]{ \label{fig:subfig:a} \includegraphics[scale0.7]{Figs/.....…

MeterSphere本地化部署实践

项目结构 搭建本地环境 安装JDK11&#xff0c;配置好JDK环境&#xff0c;系统同时支持JDK8和JDK11安装IEAD&#xff0c;配置JDK环境配置maven环境,IDEA配置(解压可以直接使用)无限重置IDEA试用期配置redis环境(解压可以直接使用) 配置kafka环境 安装mysql-5.7环境&#xff…

九州金榜|在孩子家庭教育中放手不放任

家庭教育&#xff0c;是每个父母都要面临的事情&#xff0c;也是每个家庭都要经历的&#xff0c;但是在目前的家庭教育中&#xff0c;孩子都是由父母规划&#xff0c;在一定程度上会对孩子的成长产生影响&#xff0c;如何科学家庭教育&#xff0c;九州金榜家庭教育有以下观点&a…

论文阅读笔记AI篇 —— Transformer模型理论+实战 (三)

论文阅读笔记AI篇 —— Transformer模型理论实战 &#xff08;三&#xff09; 第三遍阅读&#xff08;精读&#xff09;3.1 Attention和Self-Attention的区别&#xff1f;3.2 Transformer是如何进行堆叠的&#xff1f;3.3 如何理解Positional Encoding&#xff1f;3.x 文章涉及…

【蓝桥杯EDA设计与开发】立创开源社区分享的关于蓝桥被EDA真题与仿真题的项目分析

立创开源社区内有几个项目分享了往年 EDA 设计题目与仿真题&#xff0c;对此展开了学习。 【本人非科班出身&#xff0c;以下对项目的学习仅在我的眼界范围内发表意见&#xff0c;如有错误&#xff0c;请指正。】 项目一 来源&#xff1a;第十四届蓝桥杯EDA赛模拟题一 - 嘉立…