1、给定一个字符串判断是否为一定的格式
可以直接调用String.matches()方法判断或是用Pattern.compile()和Pattern.matcher()来判断。
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PatternTest {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
while(s.hasNext())
{
String str = s.next();
Pattern p1 = Pattern.compile("\\d{4}-\\d{1,2}-\\d{1,2}");
Matcher m1 = p1.matcher(str);
Pattern p2 = Pattern.compile("\\d{1,2}/\\d{1,2}/\\d{4}");
Matcher m2 = p2.matcher(str);
if(str.matches("[1]+[01]+"))
{
System.out.println(str+"is a binary number");
}else
{
System.out.println(str+"is not a binary number");
}
if(m1.matches()||m2.matches())
{
System.out.println(str+"is a legal date");
}
else{
System.out.println(str+"is a illegal date");
}
}
}
}