在Java裏面: java
Pattern –git
java.util.regex
類 Patternspa
表達式.net |
含義對象 |
示例ci |
||||||||||||||
\d字符串 |
表示數字 一個get |
String str = "3";it boolean boo = str.matches("\\d");io System.err.println(boo);// true //聲明聲明格式編譯成Pattern對象 Pattern p = Pattern.compile("\\d"); boolean boo2 = p.matcher(str).matches(); System.err.println(boo2); |
||||||||||||||
數量詞 + * {2,4} {2,} {5} |
0~1個 1~N個 0~N個 2~4個 2~M個 5個 |
|||||||||||||||
表達式: . 點 \D \w
[ .. …] 裏面的值可選的 |
表示是任意字符 非數字 [a-zA-Z] |
.* - 任意0~N個字符。
|
||||||||||||||
( ) 必須的 |
String類的方法:
1:trim – 去掉兩邊的空格。
public class Demo02 {
public void test1() {
String str = " XX YY ";
//str= str.trim();
//System.err.println(">"+str+"<");
//去掉全部的空格
str = str.replace(" ", "");
System.err.println(">"+str+"<");
}
}
adfasdfas.@qq.com – 不是
使用正則驗證:
@Test
public void test2(){
String regex = ".{3,}(.[a-z]{3,})@[a-z0-9]{2,6}\\.(com|cn|net|org|gov)";
Scanner sc = new Scanner(System.in);
while(true){
String mail = sc.nextLine();
boolean boo = mail.matches(regex);
System.err.println(boo);
}
}
@Test
public void test3() throws Exception {
Scanner sc = new Scanner(System.in);
String pwd = "";
int i = 0;
while (i < 3) {
System.err.println("plz enter your pwd:");
pwd = sc.nextLine();
if (pwd.length() < 6) {
System.err.println("小於6位");
} else {
boolean boo = pwd.matches("\\d*[a-z]+\\d*");
boolean boo2 = pwd.matches("[a-z]*\\d+[a-z]*");
if (boo && boo2) {
System.err.println("成功了");
break;
}
}
if (i == 2) {
System.err.println("輸入超過次數\n");
return;
}
i++;
}
System.err.println("你的密碼是:" + pwd);
}
用戶輸入任意的字符:
計算裏面的字符,數字,其餘字符的個數:
Kd48&k - >
Letter : 3
Number : 2
Other : 1
@Test
public void test4() {
Scanner sc = new Scanner(System.in);
while (true) {
String str = sc.nextLine();
int letter = 0;
int number = 0;
int others = 0;
for (int i = 0; i < str.length(); i++) {
if (Character.isLetter(str.charAt(i))) {
letter++;
} else if (Character.isDigit(str.charAt(i))) {
number++;
} else {
others++;
}
}
System.err.println("letter:" + letter + "," + number + "," + others);
}
}
@Test
public void test5() {
Scanner sc = new Scanner(System.in);
while (true) {
String str = sc.nextLine();
// 字符
String str1 = str.replaceAll("[^a-z]", "");
System.err.println(str1 + "," + str1.length());
String str2 = str.replaceAll("[^0-9]", "");
System.err.println(str2 + "," + str2.length());
String other = str.replaceAll("[a-z0-9]", "");
System.err.println(other + "," + other.length());
}
}
\d
\.
+,*,?
^ - 匹配字符的開始
[^a] – 不是a
{n,m}
()
[a-z0-9A-Z_] = \w