JAVA 正则表达式

public static void main( String args[] ){
       String REGEX = "\bcat\b";
       String INPUT = "cat cat cat cattie cat";
       Pattern p = Pattern.compile(REGEX);
       Matcher m = p.matcher(INPUT); // 获取 matcher 对象
       int count = 0;
       while(m.find()) {
         count++;
         System.out.println("Match number "+ count);
         System.out.println("start(): "+ m.start());
         System.out.println("end(): "+ m.end());
         System.out.println("end(): "+ m.group());
      }
   }

正则表达式

.     匹配除" "之外的任何单个字符
^     开始
$     结束
*     次或多次
+     一次或多次
?     零次或一次
{n}   正好 n 次
{n,}  至少匹配 n 次
{n,m} n次(含)到m次(含)
x|y 匹配 x 或 y
[xyz]  字符集。匹配包含的任一字符。例如,"[abc]"匹配"plain"中的"a"。
[^xyz] 反向字符集。匹配未包含的任何字符。例如,"[^abc]"匹配"plain"中"p","l","i","n"。
[a-z]字符范围
[^a-z]反向范围字符
d   数字字符匹配。等效于 [0-9]。
D   非数字字符匹配。等效于 [^0-9]。
f   换页符匹配。等效于 x0c 和 cL。
   换行符匹配。等效于 x0a 和 cJ。
   匹配一个回车符。等效于 x0d 和 cM。
s   匹配任何空白字符,包括空格、制表符、换页符等。与 [ f v] 等效。
S   匹配任何非空白字符。与 [^ f v] 等效。
   制表符匹配。与 x09 和 cI 等效。
v   垂直制表符匹配。与 x0b 和 cK 等效。
w   匹配任何字类字符:字母、数字和下划线。与"[A-Za-z0-9_]"等效。
W   与任何非单词字符匹配。与"[^A-Za-z0-9_]"等效

(pattern) 匹配 pattern 并捕获该匹配的子表达式
 

String类


   boolean matches(regex)
   replaceAll(String regex, String replacement)
   replaceFirst(String regex, String replacement)
   split(String regex)

Pattern类


   Pattern p = Pattern.compile("a*b");
   Matcher m = p.matcher("aaaaab");
   boolean b = m.matches();

   或者Pattern.matches("a*b", "aaaaab")

       对于多次使用的,推荐用Pattern p = Pattern.compile("a*b");,效率高些。

       注意:Matcher不是线程安全的。

Matcher类


  Matcher.matches() 需要全部匹配
  Matcher.lookingAt() 尝试将从区域开头开始的输入序列与该模式匹配。
     注意:1.从第一个字符开始匹配
                2.部分匹配即可。

  Matcher.find()  部分匹配,匹配到的字符串可以在任何位置

  Mathcer.start()/ Matcher.end()/ Matcher.group()

    当使用matches(),lookingAt(),find()执行匹配操作后,就可以利用以上三个方法得到更详细的信息.
      start()返回匹配到的子字符串在字符串中的索引位置.
      end()返回匹配到的子字符串的最后一个字符在字符串中的索引位置.
      group()返回匹配到的子字符串

  

原文地址:https://www.cnblogs.com/caoshouling/p/12200428.html