一、练习
package com.jun.regexp;
/**
* 电子邮件验证
*/
public class Homework01 {
public static void main(String[] args) {
/**
* 只能有一个@
* @前面是用户名,可以是a-z,A-Z 0-9 _-字符
* @后面是域名,域名只能是英文字母
*/
String content ="2869574500@qq.com";
String regStr ="[\\w-]+@([a-zA-Z]+\\.)+[a-zA-Z]+";
if (content.matches(regStr)){
System.out.println("验证通过");
}else {
System.out.println("验证失败");
}
}
}
package com.jun.regexp;
public class Homework02 {
public static void main(String[] args) {
//验证是不是整数或者小数(考虑正数和负数)
String content ="-0.89";
String regStr ="^[-+]?([1-9]\\d*|0)(\\.\\d+)?$";
if (content.matches(regStr)){
System.out.println("格式正确");
}else {
System.out.println("格式错误");
}
}
}
package com.jun.regexp;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Homework03 {
public static void main(String[] args) {
String content ="http://www.baidu.com:8080/asd/ee/yyy///head@#$.htm";
String regStr ="^([a-zA-Z]+)://([a-zA-Z.]+):(\\d+)[\\w-/]*/([\\w.@#$]+)$";
Pattern pattern = Pattern.compile(regStr);
Matcher matcher = pattern.matcher(content);
if (matcher.matches()){//整体匹配 成功可以通过group(x),获取对应分组的内容
System.out.println("整体匹配:"+matcher.group(0));
System.out.println("协议:"+matcher.group(1));
System.out.println("域名:"+matcher.group(2));
System.out.println("端口:"+matcher.group(3));
System.out.println("文件:"+matcher.group(4));
}else {
System.out.println("匹配失败");
}
}
}