java校验正则表达式1.在java中写正则表达式时需要注意转义
public class test {
public static void main(String[] args) {
//在java中第⼀个"\"为转义
String regex = "^[^\\s]+$";  //不包含空格
String content = "a a";
Pattern pattern = Patternpile(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:"<%=ContextPath()%>/test/testAction_checkAttrRule.action",
dataType:"json",
success:function(data){
if(data){时间正则表达式java
alert("校验通过")
}else{
alert("校验失败")
}
}
});
}
java代码
package xxxx;
import java.io.IOException;
import Matcher;
import Pattern;
import t.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) {
}
private String regex;
public String getRegex() {
return regex;
}
public void setRegex(String regex) {
< = regex;
}
/**
* 验证正则表达式是否正确
* @throws IOException
*/
public void checkAttrRule() throws IOException{
//regex等于^[^\s]+$  不需要对"\"进⾏转义
Pattern pattern = Patternpile(regex);
Matcher matcher = pattern.matcher(content);
//System.out.println(matcher.matches());
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。