用到类有:java.util.regex.Pattern;java.util.regex.Matcher
- Pattern类的作用在于编译正则表达式后创建一个匹配模式.
- Matcher类使用Pattern实例提供的模式信息对正则表达式进行匹配
- Pattern complie(String regex)
由于Pattern的构造函数是私有的,不可以直接创建,所以通过静态方法compile(String regex)方法来创建,将给定的正则表达式编译并赋予给Pattern类 - Pattern.matcher(CharSequence input) 对指定输入的字符串创建一个Matcher对象
- Matcher :boolean matches() 最常用方法:尝试对整个目标字符展开匹配检测,也就是只有整个目标字符串完全匹配时才返回真值.
Pattern integer = Pattern.compile("^\\d+$|-\\d+$"); // 判断是否为整数
Pattern demical = Pattern.compile("\\d+\\.\\d+$|-\\d+\\.\\d+$");// 判断是否为小数
Matcher matcherInteger = integer.matcher(content);
Matcher matcherDemical = demical.matcher(content);
System.out.println("整数:" + matcherInteger.matches() + ",小数:" + matcherDemical.matches());
关于Pattern和Matcher的具体用法,可以参考
点击打开链接