正则表达式在js端和java端的应用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cl11992/article/details/86289680

一、介绍

有的时候需要使用正则表达式在js端和java端来判断一些变量,在这里面记录一下js端和java端的使用方法

二、js端正则表达式的应用

注意:js端定义正则(两遍需要有/)

var regex = /^[1-9]\d*$/;

//js端判断输入框是否满足正则要求
var count = $("#count").val();	//数量
var regex = /^[1-9]\d*$/;		//正整数
if (count != "") {
    if (!regex.test(count)) {
    	alert('数量满足正则要求');
    	return false;
    } 
    alert('数量不满足正则要求');
}

三、java端正则表达式的应用

注意:java定义正则(需要转义)

String regEx = "^[1-9]\\d*$";

//java端判断输入框满足正则要求
public static void main(String[] args) {
    // 要验证的字符串
    String str = "30a";
    // 数量验证规则
    String regEx = "^[1-9]\\d*$";
    // 编译正则表达式
    Pattern pattern = Pattern.compile(regEx);
    // 忽略大小写的写法
    // Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(str);
    // 字符串是否与正则表达式相匹配
    boolean rs = matcher.matches();
    if(!re){
    	System.out.println("字符串满足正则要求");
    }else{
		System.out.println("字符串不满足正则要求");
    }
}

猜你喜欢

转载自blog.csdn.net/cl11992/article/details/86289680
今日推荐