Java初学笔记(八):正则表达式

12 篇文章 0 订阅


JUnit

  1. @Test
  2. @BeforeEach
  3. @AfterEach
  4. @BeforeAll
  5. @AfterAll
  6. @Disabled
  7. 传送门


正则表达式

  1. boolean str.matchs(String regex)
  2. 正则字符串不同于普通字符串, 特殊字符需要转义, 用普通字符串表示时就需要再次转义

匹配规则

  1. .任意字符(默认不含换行符\n)
  2. \d数字
  3. \w字母, 数字, 下划线
  4. \s空白字符
  5. \D等同[^\d], 非数字
  6. \W等同[^\w]
  7. \S等同[^\s]
  8. *任意数量>=0
  9. +一个或多个>=1
  10. ?0/1
  11. {n}n个字符
  12. {n,m}n~m个字符(书写不能留空格)
  13. {n,}>=n个字符(书写不能留空格)

复杂规则

  1. ^$匹配开头和结尾
  2. [0-9a-zA-Z]匹配指定范围
  3. [^...]排除范围
  4. |或规则匹配
  5. ()括号表示一组或范围, 可以结合|使用, 对于单字符的|, 等效字符的[]

分组匹配

  1. java.util.regex.*

  2. String.matches()不变获取分组内容, 使用Pattern对象匹配Matcher对象``Matcher.group(index)`

  3. 分组匹配:

     Pattern p = Pattern.compile("(\\d{3,4})\\-(\\d{7,8})"); // 编译正则表达式       
     Matcher m = p.matcher("010-12345678");      // 匹配成功返回Matcher对象, 否则空Matcher对象
     m.matches();                // 判断是否匹配true/false, 成功后才能调用group
     String m0 = m.group(0);     // 返回整个匹配的字符串
     String mn = m.group(n);     // 返回第n个分组的字符串内容
    

非贪婪匹配

  1. 正则表达式的数量修饰符默认是贪婪匹配, 即尽可能多的匹配
  2. 在数量修饰符后面加上?即可使用非贪婪匹配规则, 是一种弹性匹配规则

搜索和替换

分割字符串

String.split()方法可以传入正则表达式:

"a b c".split("\\s");               // { "a", "b", "c" }
"a b  c".split("\\s");              // { "a", "b", "", "c" }
"a, b ;; c".split("[\\,\\;\\s]+");  // { "a", "b", "c" }
搜索

Matcher.find()可以在整串中查找匹配串

import java.util.regex.*;
public class Main {
    public static void main(String[] args) {
        String s = "the quick brown fox jumps over the lazy dog.";
        Pattern p = Pattern.compile("\\wo\\w");
        Matcher m = p.matcher(s);
        while (m.find()) {
            String sub = s.substring(m.start(), m.end());
            System.out.println(sub);
        }
    }
}
替换

String.replaceAll(regex, repl)方法可以传入正则表达式替换

public class Main {
    public static void main(String[] args) {
        String s = "The     quick\t\t brown   fox  jumps   over the  lazy dog.";
        String r = s.replaceAll("\\s+", " ");
        System.out.println(r);  // "The quick brown fox jumps over the lazy dog."
    }
}
反向引用

在使用String.replaceAll时, 可以使用$1, $2来反向引用正则表达式匹配的分组, 从而可以进行更复杂的替换操作
String.replaceAll内部直接调用的是Matcher.replaceAll

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值