JAVA中正则表达式的入门与使用

[复制链接]
发表于 2025-9-27 01:51:45 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
JAVA中正则表达式的入门与使用
一,底子概念

正则表达式(Regex) 用于匹配字符串中的特定模式,Java 中通过 java.util.regex 包实现,焦点类为:
Pattern:编译后的正则表达式对象。
Matcher:用于在输入字符串中查找匹配项。
二,怎样快速入门

1,编译正则表达式
  1. Pattern pattern = Pattern.compile("你的正则表达式");
复制代码
2,创建匹配器
  1. Matcher matcher = pattern.matcher("要匹配的字符串");
复制代码
3,实行匹配

常用方法:

  • find():查找下一个匹配项。
  • matches():查抄整个字符串是否匹配。
  • group():获取匹配的子字符串。
三,焦点语法

1,根本元字符

元字符寄义示例.匹配恣意单个字符(换行除外)“a.c” 匹配 “abc”, “a2c”^匹配字符串开头“^hello” 匹配 “hello…”$匹配字符串末端“world$” 匹配 “…world”*匹配前面的元素 0次或多次“a*” 匹配 “”, “a”, “aaa”+匹配前面的元素 1次或多次“a+” 匹配 “a”, “aaa”?匹配前面的元素 0次或1次“a?” 匹配 “”, “a”[ ]匹配字符会合的恣意一个字符[abc] 匹配 “a”, “b”, “c”|逻辑或(匹配左侧或右侧)“cat|dog” 匹配 “cat"或"dog”2,量词与分组


  • 量词:{n}(n次)、{n,}(至少n次)、{n,m}(n到m次) 示例:“a{2}” 匹配 “aa”。
  • 分组:(…) 将子表达式分组,可用于捕获或引用。 示例:“(\d{3})-(\d{4})” 捕获电话号码的区号和号码。
3,预界说字符类

字符类寄义\d匹配数字(0-9)\D匹配非数字\w匹配字母、数字、下划线\W匹配非单词字符\s匹配空缺字符(空格、换行)\S匹配非空缺字符四、场景应用

1,验证邮箱格式
  1. String email = "[email protected]";
  2. Pattern pattern = Pattern.compile("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$");
  3. Matcher matcher = pattern.matcher(email);
  4. boolean isValid = matcher.matches(); // true 或 false
复制代码
2,提取电话号码
  1. String text = "电话:138-1234-5678";
  2. Pattern pattern = Pattern.compile("\\d{3}-\\d{4}-\\d{4}");
  3. Matcher matcher = pattern.matcher(text);
  4. if (matcher.find()) {
  5.     System.out.println(matcher.group()); // 输出 "138-1234-5678"
  6. }
复制代码
3,更换字符串
  1. String text = "价格:$99.99";
  2. Pattern pattern = Pattern.compile("\\$\\d+\\.\\d{2}");
  3. Matcher matcher = pattern.matcher(text);
  4. String replaced = matcher.replaceAll("¥100.00"); // 替换为 ¥100.00
复制代码
4, 分割字符串
  1. String csv = "apple,banana,cherry";
  2. String[] fruits = csv.split(","); // 输出 ["apple", "banana", "cherry"]
复制代码
五、正则使用tips

1,转义字符

在 Java 字符串中,反斜杠 \ 须要转义为 \。
示例:正则表达式 \d 在代码中写为 “\d”。
2,性能优化

频仍使用正则时,发起预编译 Pattern 对象:
  1.    private static final Pattern EMAIL_PATTERN = Pattern.compile("...");
复制代码
3,边界匹配

使用 ^ 和 $ 确保匹配整个字符串,而非子串:
比方"^start" 匹配以 “start” 开头的字符串,“end$” 匹配以 “end” 末端的字符串。
4,分组捕获

使用 () 分组,通过 group(int) 获取子匹配结果:
  1.    Pattern pattern = Pattern.compile("(\\d{3})-(\\d{4})");
  2.    Matcher matcher = pattern.matcher("123-4567");
  3.    System.out.println(matcher.group(1)); // 输出 "123"
复制代码
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表