仅含有数字和字母
String regex1 =
"^[a-z0-9A-Z]+$";
String regex2 ="^[a-z0-9]+$/i";
^
Start of string,字符串的开始
[a-z0-9]
a or b or c or … z or 0 or 1 or … 9 , a 或 b 或 c 或 … z 或 0 或 1 或 … 9
+
one or more times (change to * to allow empty string)一次或多次(更改为 * 以允许空字符串)
$
end of string ,字符串结尾
/i
case-insensitive ,不区分大小写
用法如下:
private static String regex = "^[a-z0-9A-Z]+$";
private static String [] test = {"123a","2143)","452","as sd","*&^%$","哈喽"};
public static void main(String[] args) {
Pattern pattern = Pattern.compile(regex);
for (int i = 0; i < test.length; i++) {
Matcher matcher = pattern.matcher(test[i]);
System.out.println("matches==>>"+matcher.find() +" test==" + test[i]);
}
}
matcher.find() 和 matcher.matches() 区别
Matcher matcher = Pattern.compile(“123”).matcher(str); //str待匹配的字符串
matcher.matches() 或者 matcher.find()
matcher:整体匹配,整个字符串与pattern的匹配规则完全匹配才返回true。对于固定的匹配规则,如Pattern.compile(“123”),字符串长度顺序都一样才返回true。上例中,str = “123” matcher.matches() 才返回true,否则返回false。
find:局部匹配,字符串具有与pattern的规则匹配的时候返回true。上例中,str只要包含"123" matcher.find就返回true,否则返回false。