正则表达式工具:
在线正则表达式测试https://tool.oschina.net/regex/
身份证正则表达式:[12344568]\d{16}[0-9xX]
1.正则表达式介绍
2.正则表达式字符
3.元字符
h[ae]llo 057[0-9] [ABCD]
4.多次重复
\d{6} \d{3,4}-\d{7,8} [A-Z][a-z]+ [A-Z][a-z]* | [A-Z][a-z]+\s[A-Z][a-z]*
5.定位匹配、贪婪模式(默认)、非贪婪模式
6.表达式分组
(\d{4})||(\d{6}) ^([\u4e00-\u9fa5][A-Z])-([0-9A-Z]{5})$ ^([\u4e00-\u9fa5]{2,8})|([A-Z][a-z]+\s[A-Z][a-z]*)
7.JavaScript表单验证
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Insert title here</title> 6 </head> 7 <body> 8 <form action="#" method="post" id="frmInfo"> 9 <div id="err" style="color:red"> 10 11 </div> 12 <div> 13 姓名:<input id="name" name="name"/> 14 </div> 15 <div> 16 身份证:<input id="idno" name="idno"/> 17 </div> 18 <div> 19 <input type="submit" /> 20 </div> 21 </form> 22 <script type="text/javascript" src="js/jquery-3.4.1.js"></script> 23 <script type="text/javascript"> 24 $("#frmInfo").submit(function(){ 25 //在JS中定义正则表达式对象只需要在/正则表达式/ 26 var regex1=/^[\u4e00-\u9fa5]{2,8}$/; 27 var regex2=/^[1234568]\d{16}[0-9Xx]$/ 28 var name=$("#name").val(); 29 var idno=$("#idno").val(); 30 if(regex1.test(name)==false){//利用正则校验数据 31 $("#err").text("无效姓名"); 32 return false; 33 }else if(regex2.test(idno)==false){ 34 $("#err").text("无效身份证"); 35 return false; 36 } 37 else{ 38 alert("验证通过,准备提交"); 39 return true 40 } 41 42 }) 43 44 </script> 45 </body> 46 </html>
8.Java中Web页面信息提取
1 package regex; 2 3 import java.io.BufferedReader; 4 import java.io.FileInputStream; 5 import java.io.FileNotFoundException; 6 import java.io.InputStreamReader; 7 import java.util.regex.Matcher; 8 import java.util.regex.Pattern; 9 10 public class RegexSample { 11 public static void main(String[] args) { 12 StringBuilder content = new StringBuilder(); 13 try { 14 FileInputStream fis = new FileInputStream("F:/workspace/regex/WebContent/sample.html"); 15 InputStreamReader isr = new InputStreamReader(fis,"UTF-8"); 16 BufferedReader bufferedReader = new BufferedReader(isr); 17 18 String lineText = ""; 19 while((lineText = bufferedReader.readLine()) != null) { 20 // System.out.println(lineText); 21 content.append(lineText + "\n"); 22 } 23 bufferedReader.close(); 24 System.out.println(content); 25 26 } catch (Exception e) { 27 // TODO Auto-generated catch block 28 e.printStackTrace(); 29 } 30 31 //1.创建正则表达式对象 32 Pattern p = Pattern.compile("<li>([\\u4e00-\\u9fa5]{2,10})([a-zA-Z]+)</li>"); 33 //2.匹配正则表达式 34 Matcher m = p.matcher(content); 35 //3.查找匹配的结果 36 while(m.find()) { 37 // System.out.println(m.group(0)); 38 String chs = m.group(1); 39 String eng = m.group(2); 40 System.out.println(chs + "-" + eng); 41 } 42 } 43 }