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());
}
}