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的使用分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:http://bianchenghao.cn/32574.html