在开发过程中,有很多地方可以用正则表达式做校验,如下是我在开发过程中,用正则表达式做校验的小例子,没有系统性,仅记录。
package com.bijian.test; public class Test { public static void main(String[] args) { String str = "12"; //小数校验:整数部分最多15位,小数部分最多2位,包括0 //boolean isMatch = str.matches("^(-)?([0]|([1-9]\\d{0,15}))(\\.\\d{0,2})?"); //小数校验:整数部分长度不控制,小数部分长度也不控制,包括0 //boolean isMatch = str.matches("^(-)?([0]|([1-9]\\d+))(\\.\\d+)?"); //只能输入正数和负数的正则表达式 //boolean isMatch = str.matches("^(-)?[1-9][0-9]*$"); //整数(包括0)的正则 //boolean isMatch = str.matches("^[-+]?\\d+$"); //小数校验:整数部分长度不控制,小数部分长度也不控制,包括0,前面可带正号或负号 boolean isMatch = str.matches("^[-+]?\\d+$"); System.out.println(isMatch); } }
说明:
d+表示至少1个、最多不限制的数字串
[0-9]*就表示至少可以0个、最多不限制的数字串
[0-9]{1,4}表示1~4个数字
[a-z]和上面[0-9]的理解类似
[^0-9a-za-z]表示除了字母、数字以外的其它字符
附:常用的正则表达式