训练题目:
1.匹配验证码(4位或者6位)
7777 888888
(^\d{4}) 对两个整体进行2选1
2.匹配车牌号
冀A-U888G 或 冀A-88888
^([冀黑粤冀][A-Z])-([0-9A-Z]{5})$
3.匹配中文(使用unicode码)
张三
^[\u4e00-\u9fa5]{2,8}$
2.表单验证
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="#" method="post" id="frmInfo">
<div id="err" style="color:red">
</div>
<div>
姓名:<input id="name" name="name">
</div>
<div>
身份证:<input id="idno" name="idno">
</div>
<div>
<input type="submit">
</div>
</form>
<script type="text/javascript">
document.getElementById("frmInfo").onsubmit = function(){
//在JS中定义正则表达式对象只需要在/正则表达式/,即可创建正则表达式对象
var regex1 = /^[\u4e00-\u9fa5]{2,8}$/;
var regex2 = /^[1234568]\d{16}[0-9xX]$/;
var name = document.getElementById("name").value;
var idno = document.getElementById("idno").value;
if(regex1.test(name) == false){//利用正则数据校验
document.getElementById("err").innerHTML = "无效姓名";
return false;//返回false,则onsubmit 不提交表单;
}else if(regex2.test(idno) == false){
document.getElementById("err").innerHTML = "无效身份证号";
return false;
}else{
alert("验证通过,准备提交");
return true;//返回true,提交表单
}
}
</script>
</body>
</html>
3页面提取
package com.imooc.regex;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexSample {
public static void main(String[] args) {
StringBuilder content = new StringBuilder();
try {
FileInputStream fis = new FileInputStream("D:\\software\\Eclipse\\eclipse workspace\\regex\\WebContent\\sample.html");
InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
BufferedReader bufferedReader = new BufferedReader(isr);
String lineText = "";
while((lineText = bufferedReader.readLine()) != null) {
// System.out.println(lineText);
content.append(lineText + "\n");
}
bufferedReader.close();
System.out.println(content);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//1.创建正则表达式对象
Pattern p = Pattern.compile("<li>([\\u4e00-\\u9fa5]{2,10})([a-zA-Z]+)</li>");
//2.匹配正则表达式
Matcher m = p.matcher(content);
//3.查找匹配的结果
while(m.find()) {
// System.out.println(m.group(0));
String chs = m.group(1);
String eng = m.group(2);
System.out.println(chs + "-" + eng);
}
}
}