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();

 

 

 

 

  • 10
    点赞
  • 45
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值