JAVA Pattern.matches的使用


1.首先阅读Pattern.matches的API:

boolean java.util.regex.Pattern.matches(String regex, CharSequence input)


Compiles the given regular expression and attempts to match the given input against it. 

An invocation of this convenience method of the form 

 Pattern.matches(regex, input);
behaves in exactly the same way as the expression 
 Pattern.compile(regex).matcher(input).matches()

If a pattern is to be used multiple times, compiling it once and reusing it will be more efficient than invoking this method each time. 
Parameters:regex The expression to be compiledinput The character sequence to be matchedReturns:whether or not the regular expression matches on the inputThrows
:PatternSyntaxException - 
If the expression's syntax is invalid

 

什么意思,看不懂没关系,看下面的例子

 String tx ="s_safasfasfqewgsvzvdsvgf.";
 boolean t = Pattern.matches("^[a-zA-Z]\\w*$", tx);
 System.out.println(t);

代码的意思就是  :字符串tx是不是匹配正则表达式^[a-zA-Z]\\w*$;,如果匹配就返回ture;如果不匹配就返回false。

 

知识点2:^[a-zA-Z]\\w*$ 

^表示正则表达式的开始;

$表示正常表达式的结尾;

[a-zA-z]表示任意一个英文字母,不区分大小写

\\w* 表示任意一个字符,字符类型为:数字,下划线和字母

结合起来就是:一个以字母开头的以,下划线和数组字母构成的字符串!

 

 

现在我们在来看看JDK的文档:

boolean java.util.regex.Pattern.matches(String regex, CharSequence input)


Compiles the given regular expression and attempts to match the given input against it. 

An invocation of this convenience method of the form 

Pattern.matches(regex, input);
behaves in exactly the same way as the expression 
Pattern.compile(regex).matcher(input).matches()

If a pattern is to be used multiple times, compiling it once and reusing it will be more efficient than invoking this method each time. 
Parameters:regex The expression to be compiledinput The character sequence to be matchedReturns:whether or not the regular expression matches on the inputThrows
:PatternSyntaxException - 
If the expression's syntax is invalid

说明还可以这样使用:

boolean ty=Pattern.compile("^[a-zA-Z]\\w*$").matcher(tx).matches();

 

 

 

 

你可能感兴趣的:(JAVA Pattern.matches的使用)