美文网首页
Using Java regex

Using Java regex

作者: ibyr | 来源:发表于2016-12-23 00:11 被阅读23次

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.

相关文章

网友评论

      本文标题:Using Java regex

      本文链接:https://www.haomeiwen.com/subject/dughvttx.html