Using Java regex

Not to introduce regex grammar(If you want to know, you search it.), but some key points about using java regex.

1. How to use regex in Java?

String s1 = "ab12cd34ef";
String pattern = "(\\d+)([a-z]+)";
Pattern p = Pattern.compile(pattern);  // First step: Pattern compile regex.
Matcher m = p.matcher(s1);             // Second step: matcher the str.
while (m.find()) {                     // must find() before any group().
  System.out.println(m.group());  //== group(0). output: 12cd \n 34ef.
  //System.out.println(m.group(1));  //output: 12 \n 34. The first ().
  //System.out.println(m.group(2));  //output: cd \n ef. The second ().
}

2. String matches()

// Show code first.
String s = "ab12cd34";
boolean b = s.matches("[a-z]+\\d+[a-z]{0,}\\d+");  // b is true.
boolean b1 = s.matches("[a-z]+\\d+");  // b1 is false.
// s.matches() is to match the whole string.

So what happened in matches() ?

s.matches(String regex)  -> return Pattern.matches(regex, this).
----
Pattern.matches(regex, this) ->
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(this);  // this means the string itself.
return m.matches();
----
m.matches() -> return match(from, ENDANCHOR);  
// ENDANCHOR = 1, which means to match all the input.

So in String.matches(String regex), regex match all the string.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容