java校验正则表达式

1.在java中写正则表达式时需要注意转义

public class test {
    public static void main(String[] args) {
        //在java中 第一个"\"为转义   
        String regex = "^[^\\s]+$";  //不包含空格 
        String content = "a a";
        Pattern pattern = Pattern.compile(regex);  

        Matcher matcher = pattern.matcher(content);
        System.out.println(matcher.matches());   //false
    }
}

2.ajax传参,赋值正则表达式
jsp代码:

<input type="text" name="regex"  id="regex" value="^[^\s]+$"/>

<input type="text" name="testContent"  id="testContent" value="a a"/>

<input type="button" value="校验正则" onclick="checkAttrRule()"/>

javascript代码:

    function checkAttrRule(){
         var con = $("#testContent").val();    //需要测试的内容
         var regCon = $("#regex").val();       //需要匹配的正则

         $.ajax({
            data:{
                "content":con,
                regex : regCon
            },
            url:"<%=request.getContextPath()%>/test/testAction_checkAttrRule.action",
            dataType:"json",
            success:function(data){
                 if(data){
                     alert("校验通过")
                 }else{
                     alert("校验失败")
                 }
            }
        });
    }

java代码

package xxxx;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;


@Scope("prototype")
@Controller("testAction")
public class TestAction{

    private String content;
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }

    private String regex;
    public String getRegex() {
        return regex;
    }
    public void setRegex(String regex) {
        this.regex = regex;
    }
    /**
     * 验证正则表达式是否正确
     * @throws IOException
     */
    public void checkAttrRule() throws IOException{
        //regex等于^[^\s]+$  不需要对"\"进行转义
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(content);
        //System.out.println(matcher.matches());
        response.getWriter().print(matcher.matches());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值