这里写了一个简单的正则表达式使用例子:通过Pattern和Matcher检查输入的邮箱地址是否有效
最核心的语句为:
final String regString= "\\w{3,20}@\\w+\\.(com|org|cn|net|gov)";
详细代码如下:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CheckMailAdress {
public static void main(String[] args) {
while (true) {
System.out.println("请输入邮箱地址:");
BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
try {
String buf = new String (bReader.readLine());
isMailAdressValid(buf);
} catch (IOException exception) {
// TODO: handle exception
exception.printStackTrace();
}
}
}
private static boolean isMailAdressValid (String str)
{
final String regString= "\\w{3,20}@\\w+\\.(com|org|cn|net|gov)";
Pattern pattern = Pattern.compile(regString);
Matcher matcher = null;
if(matcher == null)
{
matcher = pattern.matcher(str);
}
if(matcher.matches())
{
System.out.println(str+"是一个有效的邮件地址!");
}
else {
System.out.println(str+"不是一个有效的邮件地址!");
}
return false;
}
}
运行结果如下: