简体   繁体   English

用于java的String.matches方法的正则表达式?

[英]Regex for java's String.matches method?

Basically my question is this, why is: 基本上我的问题是这个,为什么:

String word = "unauthenticated";
word.matches("[a-z]");

returning false? 归还假? (Developed in java1.6) (用java1.6开发)

Basically I want to see if a string passed to me has alpha chars in it. 基本上我想看看传递给我的字符串是否有alpha字符。

The String.matches() function matches your regular expression against the whole string (as if your regex had ^ at the start and $ at the end). String.matches()函数将正则表达式与整个字符串相匹配(就好像你的正则表达式在开始时有^ ,在结尾有$ )。 If you want to search for a regular expression somewhere within a string, use Matcher.find() . 如果要在字符串中的某处搜索正则表达式,请使用Matcher.find()

The correct method depends on what you want to do: 正确的方法取决于您想要做什么:

  1. Check to see whether your input string consists entirely of alphabetic characters ( String.matches() with [az]+ ) 检查输入字符串是否完全由字母字符组成( String.matches()[az]+
  2. Check to see whether your input string contains any alphabetic character (and perhaps some others) ( Matcher.find() with [az] ) 检查输入字符串是否包含任何字母字符(可能还有其他字符)( Matcher.find()[az]

Your code is checking to see if the word matches one character. 您的代码正在检查该单词是否与一个字符匹配。 What you want to check is if the word matches any number of alphabetic characters like the following: 您要检查的是该单词是否与以下任意数量的字母字符匹配:

word.matches("[a-z]+");

with [az] you math for ONE character. [az]你算一个字符。

What you're probably looking for is [az]* 您可能正在寻找的是[az]*

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM