返回导航页
正则语法
正则表达式以匹配字符串中的数字
String regex = "[+-]?[0-9.]+";
正则表达式,提取单位(数字后面的部分)
String regex = "^.*\\d(.*)$";
正则原理
Java用法
//正则表达式以匹配字符串中的数字
String regex = "[+-]?[0-9.]+";
//创建一个模式对象
Pattern pattern = Pattern.compile(regex);
//创建一个Matcher对象
Matcher matcher = pattern.matcher(">234mm");
if (matcher.find()) {
System.out.print(matcher.group(0));
}
matcher的两个方法的区别
find()方法是部分匹配,是查找输入串中与模式匹配的子串,如果该匹配的串有组还可以使用group()函数。
matches()是全部匹配,是将整个输入串与模式匹配,如果要验证一个输入的数据是否为数字类型或其他类型,一般要用matches()。