使用正则表达式做基本判断。
一、代码实现
(1)引入java中自带的正则包
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
(2)简单匹配数字字符串长度
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.xie; import java.util.regex.Matcher; import java.util.regex.Pattern; public class testregex { public boolean testregex(String string) { Pattern pattern = Pattern.compile("^\\d{5,12}$"); Matcher matcher = pattern.matcher(string); if (matcher.matches()) { return true; } return false; } public static void main(String[] args) { testregex testregex = new testregex(); System.out.println(testregex.testregex("503822883")); } } |
(3)简单替换字符
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package com.xie; import java.util.regex.Matcher; import java.util.regex.Pattern; public class testregex { public String testregexreplaceall(String string , String replacestring) { Pattern pattern = Pattern.compile("godlikexie", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(string); String result = matcher.replaceAll(replacestring); return result; } public String testregexreplacefirst(String string , String replacestring) { Pattern pattern = Pattern.compile("godlikexie", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(string); String result = matcher.replaceFirst(replacestring); return result; } public static void main(String[] args) { testregex testregex = new testregex(); System.out.println(testregex.testregexreplaceall("my name is godlikexie ! godlikexie !" , "xie")); System.out.println(testregex.testregexreplacefirst("my name is godlikexie ! godlikexie !" , "xie")); } } |
结果为:
my name is xie ! xie !
my name is xie ! godlikexie !
(4)简单匹配邮箱
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.xie; import java.util.regex.Matcher; import java.util.regex.Pattern; public class testregex { public static boolean testregexemail(String string) { Pattern pattern = Pattern.compile("^(\\w-*\\.*)+@(\\w-?)+(\\.\\w{2,})+$"); Matcher matcher = pattern.matcher(string); if (matcher.matches()) { return true; } return false; } public static void main(String[] args) { testregex testregex = new testregex(); System.out.println(testregex.testregexemail("503822883@qq.com")); } } |
二、总结
总结一下。