流程

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
  @Test
  public void testRegex(){
String s = "hel*o";
Pattern pattern = Pattern.compile(s);  // * 创建正则
String source = "helllo helo hello there.";
Matcher m = pattern.matcher(source);   // * 制作Match
int i = 1;
while(m.find()){                       // * 使用 Match  --> 进行正则操作,匹配 find, matches, replaceAll, ....
   System.out.println("m:" + m);
   System.out.println(i + " matched:" + source.substring(m.start(), m.end()));
}

  }

相关类

  • Pattern 类

    • 存储正则
  • Matcher 类

    • 执行正则的工具
    • 和存储匹配的结果
  • String 类

    • 方法

      • str.replaceAll("regex", "repl")
  • 替换引用 $1, $2 —> python 中 \g<1>, \g<2>

    • str.matches("regex")

Matcher 类

  • 创建

    1
    
      pattern.matcher("操作的字符串")
  • 方法

    • 匹配

      • find() –> boolean
  • 多次重复查找

    • matches() –> boolean
  • 完整匹配

    • lookingAt() –> boolean
  • 开始段匹配

    • 重置

      • reset()
    • 替换

      • replaceAll()
      • replaceFirst()
      • 和 find() 一起使用
  • appendRepalcement()
  • appendTail()

    • 查找结果

      • group()
      • 索引
  • start()
  • end()
  • start(int groupNumber)

    • 指定 group 的 start index
  • end(int groupNumber)

    • 正则信息

      • pattern()
  • 使用的正则–>Pattern 类

    • usePattern()
  • 设置新正则

    • groupCount()
  • pattern 包含的 group 数量

    • 限定范围查找

      • 设置范围
  • region(int start, int end)

    • 查看,可以匹配的范围
  • regionStart()
  • regionEnd()

    • 特殊功能

      • find(int index_source_str)
  • 重置匹配器
  • 指定 在要匹配字符串 中,开始匹配的位置
  • 注意:不是 这个 index 不是 group 而是 str 索引