个人简介
- 大家好,我是韩慧腾。一名正在努力学JAVA的大一小白,本文章为初学的笔记,希望各位多多指教。💙
- 欢迎点赞+收藏+留言💜
- 少年自有少年狂,心向骄阳万丈光🧡
一、正则表达式
概述:正则表达式通常被用于判断语句中,用来检验某一字符串是否满足某一格式。
之前我们检验某字符串的方法:
案例:用于检验某ID号:ID号必须是六位数,前两位是大写字母,后四位是数字。
import java.util.Scanner;
/**
* @author hanhan
* date 2022/5/14 10:58
* 努力已经来不及了,你得拼命
*/
public class MathPractise {
public static void main(String[] args) {
while (true) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入用户ID号:");
String id=scanner.next();
if(checkID(id)){
System.out.println("输入ID正确");
break;
}else{
System.out.println("输入ID错误");
}
}
}
public static boolean checkID(String id){
if(id==null||id.length()!=6){
return false;
}
for(int i=0;i<id.length();i++){
if(i==0||i==1){
char c = id.charAt(i);
if(c<'A'||c>'Z'){
return false;
}
}
if(i>1){
char c=id.charAt(i);
if(c<'0'||c>'9'){
return false;
}
}
}
return true;
}
}
正则表达式版本:
import java.util.Scanner;
/**
* @author hanhan
* date 2022/5/14 10:58
* 努力已经来不及了,你得拼命
*/
public class MathPractise {
public static void main(String[] args) {
while (true) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入用户ID号:");
String id=scanner.next();
if(checkID(id)){
System.out.println("输入ID正确");
break;
}else{
System.out.println("输入ID错误");
}
}
}
public static boolean checkID(String id){
return id!=null&&id.matches("\\p{Upper}{2}\\d{4}");
}
二、正则表达式的匹配规则
匹配正则表达式的API:matches
表示非9的4位数字:[\\d&&[^9]]{4} 。支持该写法
若要求写.时候需要在前方加上\
三、正则表达式在字符串方法中的使用
/**
* @author hanhan
* date 2022/5/14 14:58
* 努力已经来不及了,你得拼命
*/
public class RegexDemo_01 {
public static void main(String[] args) {
String s="智者不入爱河hjk12345hjkj1h234建设美丽中国";
String[] split = s.split("\\w+");
for (String s1 : split) {
System.out.println(s1);
}
String s1 = s.replaceAll("\\w+", " ");
System.out.println(s1);
}
}
四、正则表达式爬取某些内容
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author hanhan
* date 2022/5/14 15:10
* 努力已经来不及了,你得拼命
* 爬取字符串中的数字、字母
*/
public class RegexDemo_02 {
public static void main(String[] args) {
String s="程序设3322计课256asdfgfd程设计\n" + "12376指导书655";
//定义一个爬取规则
String regex="\\w+";
//把这个爬取规则编译成匹配对象
Pattern compile = Pattern.compile(regex);
//得到一个内容匹配器对象
Matcher matcher = compile.matcher(s);
while(matcher.find()){
String ss= matcher.group();
System.out.println(ss);
}
}
}