java 正则的demo

2021-12-21 16:39
460
0
package com.tt.regex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexTest {
   public static void main(String[] args) {
       String text = "Hello Regex!";
       Pattern pattern = Pattern.compile("\\w+");
       // Java 中忽略大小写,有两种写法:
       // Pattern pattern = Pattern.compile("\\w+", Pattern.CASE_INSENSITIVE);
       // Pattern pattern = Pattern.compile("(?i)\\w+"); // 推荐写法
       Matcher matcher = pattern.matcher(text);
       // 遍例所有匹配的序列
       while (matcher.find()) {
           System.out.print("Start index: " + matcher.start());
           System.out.print(" End index: " + matcher.end() + " ");
           System.out.println(matcher.group());
       }
       // 创建第两个模式,将空格替换为 tab
       Pattern replace = Pattern.compile("\\s+");
       Matcher matcher2 = replace.matcher(text);
       System.out.println(matcher2.replaceAll("\t"));
   }
}

全部评论