标签:
下表显示了正则表达式的语法: 表 1.1 正则表达式语法
|
测试代码:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str="bbg";
Pattern pattern = Pattern.compile("(b*g)");
Matcher matcher = pattern.matcher(str);
System.out.println(matcher.matches());
System.out.println(pattern.matches("b*g","bbg"));
System.out.println(pattern.matches("[0-9]{6}", "200038"));
System.out.println(pattern.matches("//d{6}", "200038"));
//验证电话号码
System.out.println(pattern.matches("[0-9]{3,4}//-?[0-9]+", "021-78989799"));
getString("D:/dir1/test.txt");
getChinese("welcome to china,江西奉新,welcome,你!");
}
public static void getString(String str){
String regex = ".+/(.+)$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
if(!matcher.find()){
System.out.println("文件路径格式不正确!");
return;
}
System.out.println(matcher.group(1));
}
public static void getChinese(String str){
String regex = "[//u4E00-//u9FFF]+";//[//u4E00-//u9FFF]为汉字
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
StringBuffer sb = new StringBuffer();
while(matcher.find()){
sb.append(matcher.group());
}
System.out.println(sb);
}
public static void validateEmail(String email){
String regex = "[0-9a-zA-Z]+@[0-9a-zA-Z]+//.[0-9a-zA-Z]+";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(email);
if(matcher.matches()){
System.out.println("这是合法的Email");
}else{
System.out.println("这是非法的Email");
}
}
}
标签:
原文地址:http://www.cnblogs.com/zhengfengshaw/p/4537055.html