Using Java regex

2016-12-23  本文已影响23人  ibyr

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.

上一篇 下一篇

猜你喜欢

热点阅读