Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537 Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537
正則表達式一般用于字符串匹配,字符串查找和字符串替換。別小看它的作用,在工作學習中靈活運用正則表達式處理字符串能夠大幅度提高效率,編程的快樂來得就是這么簡單。
下面將由淺入深講解正則表達式的使用。
package test;
public class Test01 {
public static void main(String[] args) {
//字符串abc匹配正則表達式"...", 其中"."表示一個字符
//"..."表示三個字符
System.out.println("abc".matches("..."));
System.out.println("abcd".matches("..."));
}
}
輸出結果:
true
false
String類中有個matches(String regex)方法, 返回值為布爾類型,用于告訴這個字符串是否匹配給定的正則表達式。
在本例中我們給出的正則表達式為...,其中每個.表示一個字符,整個正則表達式的意思是三個字符,顯然當匹配abc的時候結果為true,匹配abcd時結果為false。
在java.util.regex包下有兩個用于正則表達式的類, 一個是Matcher,另一個Pattern。
Java官方文檔中給出對這兩個類的典型用法,代碼如下:
package test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test02 {
public static void main(String[] args) {
//[a-z]表示a~z之間的任何一個字符, {3}表示3個字符, 意思是匹配一個長度為3, 并且每個字符屬于a~z的字符串
Pattern p=Pattern.compile("[a-z]{3}");
Matcher m1=p.matcher("abc");
System.out.println(m2.matches());
}
}
輸出結果:true
Pattern可以理解為一個模式,字符串需要與某種模式進行匹配。 比如Test02中, 我們定義的模式是一個長度為3的字符串, 其中每個字符必須是a~z中的一個。
我們看到創建Pattern對象時調用的是Pattern類中的compile方法,也就是說對我們傳入的正則表達式編譯后得到一個模式對象。 而這個經過編譯后模式對象,,會使得正則表達式使用效率會大大提高,并且作為一個常量,它可以安全地供多個線程并發使用。
Matcher可以理解為模式匹配某個字符串后產生的結果。字符串和某個模式匹配后可能會產生很多個結果,這個會在后面的例子中講解。
最后當我們調用m.matches()時就會返回完整字符串與模式匹配的結果。
上面的三行代碼可以簡化為一行代碼:
System.out.println("abc".matches("[a-z]{3}"));
但是如果一個正則表達式需要被重復匹配,這種寫法效率較低。
代碼示例:
package test;
public class Test03 {
private static void p(Object o){
System.out.println(o);
}
public static void main(String[] args) {
// "X*" 代表零個或多個X
p("aaaa".matches("a*"));
p("".matches("a*"));
// "X+" 代表一個或多個X
p("aaaa".matches("a+"));
// "X?" 代表零個或一個X
p("a".matches("a?"));
// \\d A digit: [0-9], 表示數字, 但是在java中對"\\"這個符號需要使用\\進行轉義, 所以出現\\d
p("2345".matches("\\d{2,5}"));
// \\.用于匹配"."
p("192.168.0.123".matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"));
// [0-2]指必須是0~2中的一個數字
p("192".matches("[0-2][0-9][0-9]"));
}
}
輸出結果:全是true。
[]用于描述一個字符的范圍, 下面是一些例子:
package test;
public class Test04 {
private static void p(Object o){
System.out.println(o);
}
public static void main(String[] args) {
//[abc]指abc中的其中一個字母
p("a".matches("[abc]"));
//[^abc]指除了abc之外的字符
p("1".matches("[^abc]"));
//a~z或A~Z的字符, 以下三個均是或的寫法
p("A".matches("[a-zA-Z]"));
p("A".matches("[a-z|A-Z]"));
p("A".matches("[a-z[A-Z]]"));
//[A-Z&&[REQ]]指A~Z中并且屬于REQ其中之一的字符
p("R".matches("[A-Z&&[REQ]]"));
}
}
輸出結果:全是true。
關于\
在Java中的字符串中,如果要用到特殊字符, 必須通過在前面加\進行轉義。
舉個例子,考慮這個字符串"老師大聲說:"同學們,快交作業!""。 如果我們沒有轉義字符,那么開頭的雙引號的結束應該在說:"這里,但是我們的字符串中需要用到雙引號, 所以需要用轉義字符。
使用轉義字符后的字符串為"老師大聲說:\"同學們,快交作業!\"", 這樣我們的原意才能被正確識別。
同理如果我們要在字符串中使用\,也應該在前面加一個\,所以在字符串中表示為"\"。
那么如何在正則表達式中表示要匹配\呢? 答案為"\\"。
我們分開考慮:由于正則式中表示\同樣需要轉義, 所以前面的\表示正則表達式中的轉義字符\,后面的\表示正則表達式中\本身, 合起來在正則表達式中表示\。
先來看代碼示例:
package test;
public class Test05 {
private static void p(Object o){
System.out.println(o);
}
public static void main(String[] args) {
// \s{4}表示4個空白符
p(" \n\r\t".matches("\\s{4}"));
// \S表示非空白符
p("a".matches("\\S"));
// \w{3}表示數字字母和下劃線
p("a_8".matches("\\w{3}"));
p("abc888&^%".matches("[a-z]{1,3}\\d+[%^&*]+"));
// 匹配 \
p("\\".matches("\\\\"));
}
}
^在中括號內表示取反的意思[^], 如果不在中括號里則表示字符串的開頭。
代碼示例:
package test;
public class Test06 {
private static void p(Object o){
System.out.println(o);
}
public static void main(String[] args) {
/**
* ^ The beginning of a line 一個字符串的開始
* $ The end of a line 字符串的結束
* \b A word boundary 一個單詞的邊界, 可以是空格, 換行符等
*/
p("hello sir".matches("^h.*"));
p("hello sir".matches(".*r$"));
p("hello sir".matches("^h[a-z]{1,3}o\\b.*"));
p("hellosir".matches("^h[a-z]{1,3}o\\b.*"));
}
}
輸出結果:
true
true
true
false
代碼示例:
package test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test07 {
private static void p(Object o){
System.out.println(o);
}
public static void main(String[] args) {
Pattern pattern=Pattern.compile("\\d{3,5}");
String s="123-34345-234-00";
Matcher m=pattern.matcher(s);
//先演示matches(), 與整個字符串匹配.
p(m.matches());
//結果為false, 顯然要匹配3~5個數字會在-處匹配失敗
//然后演示find(), 先使用reset()方法把當前位置設置為字符串的開頭
m.reset();
p(m.find());//true 匹配123成功
p(m.find());//true 匹配34345成功
p(m.find());//true 匹配234成功
p(m.find());//false 匹配00失敗
//下面我們演示不在matches()使用reset(), 看看當前位置的變化
m.reset();//先重置
p(m.matches());//false 匹配整個字符串失敗, 當前位置來到-
p(m.find());// true 匹配34345成功
p(m.find());// true 匹配234成功
p(m.find());// false 匹配00始邊
p(m.find());// false 沒有東西匹配, 失敗
//演示lookingAt(), 從頭開始找
p(m.lookingAt());//true 找到123, 成功
}
}
如果一次匹配成功的話start()用于返回匹配開始的位置,
end()用于返回匹配結束字符的后面一個位置。
代碼示例:
package test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test08 {
private static void p(Object o) {
System.out.println(o);
}
public static void main(String[] args) {
Pattern pattern=Pattern.compile("\\d{3,5}");
String s="123-34345-234-00";
Matcher m=pattern.matcher(s);
p(m.find());//true 匹配123成功
p("start: " + m.start() + " - end:" + m.end());
p(m.find());//true 匹配34345成功
p("start: " + m.start() + " - end:" + m.end());
p(m.find());//true 匹配234成功
p("start: " + m.start() + " - end:" + m.end());
p(m.find());//false 匹配00失敗
try {
p("start: " + m.start() + " - end:" + m.end());
} catch (Exception e) {
System.out.println("報錯了...");
}
p(m.lookingAt());
p("start: " + m.start() + " - end:" + m.end());
}
}
輸出結果:
true
start: 0 - end:3
true
start: 4 - end:9
true
start: 10 - end:13
false
報錯了...
true
start: 0 - end:3
Matcher類中的一個方法group(),它能返回匹配到的字符串。
代碼示例:將字符串中的java轉換為大寫
package test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test09 {
private static void p(Object o){
System.out.println(o);
}
public static void main(String[] args) {
Pattern p=Pattern.compile("java");
Matcher m=p.matcher("java I love Java and you");
p(m.replaceAll("JAVA"));//replaceAll()方法會替換所有匹配到的字符串
}
}
輸出結果:
JAVA I love Java and you
我們要在創建模板模板時指定大小寫不敏感。
public static void main(String[] args) {
Pattern p=Pattern.compile("java", Pattern.CASE_INSENSITIVE);//指定為大小寫不敏感的
Matcher m=p.matcher("java I love Java and you");
p(m.replaceAll("JAVA"));
}
輸出結果:
JAVA I love JAVA and you
這里演示把查找到第奇數個字符串轉換為大寫,第偶數個轉換為小寫。
這里會引入Matcher類中一個強大的方法appendReplacement(StringBuffer sb, String replacement),它需要傳入一個StringBuffer進行字符串拼接。
public static void main(String[] args) {
Pattern p=Pattern.compile("java", Pattern.CASE_INSENSITIVE);
Matcher m=p.matcher("java Java JAVA JAva I love Java and you ?");
StringBuffer sb=new StringBuffer();
int index=1;
while(m.find()){
m.appendReplacement(sb, (index++ & 1)==0 ? "java" : "JAVA");
index++;
}
m.appendTail(sb);//把剩余的字符串加入
p(sb);
}
輸出結果:
JAVA JAVA JAVA JAVA I love JAVA and you ?
先看一個示例:
package test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test10 {
private static void p(Object o) {
System.out.println(o);
}
public static void main(String[] args) {
Pattern p=Pattern.compile("\\d{3,5}[a-z]{2}");
String s="005aa-856zx-1425kj-29";
Matcher m=p.matcher(s);
while (m.find()) {
p(m.group());
}
}
}
輸出結果:
005aa
856zx
1425kj
其中正則表達式"\d{3,5}[a-z]{2}"表示3~5個數字跟上兩個字母,然后打印出每個匹配到的字符串。
如果想要打印每個匹配串中的數字,如何操作呢?
分組機制可以幫助我們在正則表達式中進行分組。規定使用()進行分組,這里我們把字母和數字各分為一組"(\d{3,5})([a-z]{2})"
然后在調用m.group(int group)方法時傳入組號即可。
注意:組號從0開始,0組代表整個正則表達式,從0之后,就是在正則表達式中從左到右每一個左括號對應一個組。在這個表達式中第1組是數字, 第2組是字母。
public static void main(String[] args) {
Pattern p=Pattern.compile("(\\d{3,5})([a-z]{2})");//正則表達式為3~5個數字跟上兩個字母
String s="005aa-856zx-1425kj-29";
Matcher m=p.matcher(s);
while(m.find()){
p(m.group(1));
}
}
輸出結果:
005
856
1425
以上就是對于正則表達式的一個總結和使用說明,愿正則表達式給你帶來更愉快的編程體驗。
作者:初念初戀
原文鏈接:https://juejin.cn/post/6999944971495145502
這里是云端源想IT,幫你輕松學IT”
嗨~ 今天的你過得還好嗎?
如果你趕不上凌晨五點的日出
你不妨看看傍晚六點的夕陽
我的意思是
你可以選擇后者
- 2023.06.30 -
說起正則表達式大家應該都不陌生,今天小編給大家找了一個JavaScript正則表達式的練習,利用正則表達式進行注冊信息格式驗證,快打開你的電腦一起來練習試試吧!
注冊信息界面如下:
需求格式要求如下,開始練習前,大家要仔細閱讀要求哦!
格式要求:
1、學號項不能為空,必須為純數字,不能與數據庫中的重復,正則表達式/^\d+$/g;
2、姓名項不能為空;
3、密碼不能為空且無空格判斷空格text.split(" ").length !=1,安全等級分為3個等級:
4、確認密碼項要求與密碼項填寫的密碼一致;
5、年級項不能為空,且格式必須為第20**級,正則表達式text.search(/^\u7B2C{1}20\d+\u7EA7{1}$/) !=-1;
6、專業項不能為空,且只能以漢字開頭,結尾可以為漢字或者字母正則表達式text.search(/^[\u4e00-\u9fa5]+[a-zA-Z]*$/g) !=-1;
7、班級項不能為空且格式為專業+班級即類似電信1001格,正則表達式text.search(/^[\u4e00-\u9fa5]+\d{4}$/) !=-1;
8、手機項可以為空,格式為(+86)1*********正則表達式text.search(/^(\+86)?1\d{10}$/) !=-1。
運行效果:
正確格式輸入后運行效果:
下面小編將參考代碼奉上,聽我的!先自己試著敲代碼運行試試,實在不會了再看答案哦!
html代碼:
<!--register-->
<div style="display:block">
<div>
<span style=" font-weight: bold;"><label>注冊</label></span>
</div>
<div>
<span class="input_span"><label class="text_label">學號</label><label class="text_label" style="color:Red;">*</label></span>
<span class="input_span"><input type="text" id="studentNum_input" οnblur="checkRegisterInfo(1)"/></span>
<span><label id="studentNumCheck_label"></label></span>
</div>
<div>
<span class="input_span"><label class="text_label">姓名</label><label class="text_label" style="color:Red;">*</label></span>
<span class="input_span"><input type="text" id="name_input" οnblur="checkRegisterInfo(2)"/></span>
<span><label id="nameCheck_label"></label></span>
</div>
<div>
<span class="input_span"><label class="text_label">密碼</label><label class="text_label" style="color:Red;">*</label></span>
<span class="input_span"><input type="password" id="passwd_rigester_input" οnblur="checkRegisterInfo(3)"/></span>
<span><label id="passwdCheck_label"></label></span>
</div>
<div>
<span class="input_span" id="confirmpasswd_span"><label>確認密碼</label><label class="text_label" style="color:Red;"> *</label></span>
<span class="input_span"><input type="password" id="confirmPasswd_input" οnblur="checkRegisterInfo(4)"/></span>
<span><label id="confirmPasswdCheck_label"></label></span>
</div>
<div>
<span class="input_span"><label class="text_label">年級</label><label class="text_label" style="color:Red;">*</label></span>
<span class="input_span"><input type="text" id="grade_input" οnblur="checkRegisterInfo(5)"/></span>
<span><label id="gradeCheck_label">格式:第20**級</label></span>
</div>
<div>
<span class="input_span"><label class="text_label">專業</label><label class="text_label" style="color:Red;">*</label></span>
<span class="input_span"><input type="text" id="major_input" οnblur="checkRegisterInfo(6)"/></span>
<span><label id="majorCheck_label"></label></span>
</div>
<div>
<span class="input_span"><label class="text_label">班級</label><label class="text_label" style="color:Red;">*</label></span>
<span class="input_span"><input type="text" id="class_input" οnblur="checkRegisterInfo(7)"/></span>
<span><label id="classCheck_label">格式:電信1001</label></span>
</div>
<div>
<span class="input_span" id="phone_span"><label class="text_label">手機</label></span>
<span class="input_span"><input type="text" id="phone_input" οnblur="checkRegisterInfo(8)"/></span>
<span><label id="phoneCheck_label"></label></span>
</div>
<div class="button_div"><span><input id="register_button" type="button" οnclick="summitRegisterInfo()" value="用戶注冊"/></span></div>
</div>
<!--end register-->
</div>
就知道有的人會直接看答案~
代碼比較長,大家有耐心一點,看了答案也要自己再敲一遍哦,這樣你的體會將更深刻。
JS驗證源代碼:
/*
* 功能: 驗證注冊信息是否合法,在每次<input>控件失去聚焦時調用
* 參數: num 控件編號,指示是哪個控件觸發了該函數
* 返回值: 如果全部合法返回true,否則給予響應的錯誤提示并返回false
*/
function checkRegisterInfo(num) {
var text;
switch (num) {
//當點擊提交按鈕時校驗必填項是否為空,防止直接點擊提交按鈕
case 0:
if (document.getElementById("studentNum_input").value==""
|| document.getElementById("name_input").value==""
|| document.getElementById("passwd_rigester_input").value==""
|| document.getElementById("confirmPasswd_input").value==""
|| document.getElementById("grade_input").value==""
|| document.getElementById("major_input").value==""
|| document.getElementById("class_input").value=="") {
alert("注冊失敗,打*號的項不能為空!");
return false;
}
else
return true;
break;
//驗證學號
case 1:
text=document.getElementById("studentNum_input").value;
var check=document.getElementById("studentNumCheck_label");
//驗證是否為空
if (text=="") {
check.style.color="red";
check.innerText="學號項不能為空!";
}
//驗證格式
else if (text.search(/^\d+$/g)==-1) {
check.style.color="red";
check.innerText="學號應為純數字!";
}
else {
//驗證學號的唯一性
var xmlHttp=createXmlHttp();
xmlHttp.open("get", "Ajax.aspx?met=rigesterInfo&data=" + escape(text), true);
xmlHttp.send(null);
xmlHttp.onreadystatechange=function () {
if (xmlHttp.readyState==4 & xmlHttp.status==200) {
//服務器返回true表示該學號可用
if (xmlHttp.responseText) {
check.style.color="yellow";
check.innerText="恭喜您,該學號可用!";
}
else {
check.style.color="red";
check.innerText="您輸入的學號已存在,請重新輸入!";
}
}
}
}
break;
//驗證姓名
case 2:
text=document.getElementById("name_input").value;
var check=document.getElementById("nameCheck_label");
if (text=="") {
check.style.color="red";
check.innerText="名字項不能為空!";
}
else {
check.style.color="yellow";
check.innerText="名字項填寫正確!";
}
break;
//驗證密碼
case 3:
text=document.getElementById("passwd_rigester_input").value;
var check=document.getElementById("passwdCheck_label");
if (text=="") {
check.style.color="red";
check.innerText="密碼項不能為空!";
}
//密碼中只能有數字、字母和標點符號
else if (text.split(" ").length !=1) {
check.style.color="red";
check.innerText="密碼中不能出現空格!";
}
else {
//驗證密碼的安全級數,純數字或純字母或純標點為1級,字母+數字為2級,字母或數字任意一個+標點為3級
if ((text.search(/^[a-zA-Z]+$/g) !=-1) || (text.search(/^[0-9]+$/g) !=-1)) {
check.style.color="yellow";
check.innerText="密碼安全級別為1級!";
}
else if (text.search(/^[a-zA-Z0-9]+$/g) !=-1) {
check.style.color="yellow";
check.innerText="密碼安全級別為2級!";
}
else {
check.style.color="yellow";
check.innerText="密碼安全級別為3級!";
}
}
break;
//驗證確認密碼
case 4:
text=document.getElementById("confirmPasswd_input").value;
var check=document.getElementById("confirmPasswdCheck_label");
if (text !=document.getElementById("passwd_rigester_input").value) {
check.style.color="red";
check.innerText="兩次密碼輸入不一致!";
}
else {
check.style.color="yellow";
check.innerText="密碼確認正確!";
}
break;
//驗證年級
case 5:
text=document.getElementById("grade_input").value;
var check=document.getElementById("gradeCheck_label");
if (text=="") {
check.style.color="red";
check.innerText="年級項不能為空!";
}
else if (text.search(/^\u7B2C{1}20\d+\u7EA7{1}$/) !=-1) {
check.style.color="yellow";
check.innerText="年級項填寫正確!";
}
else {
check.style.color="red";
check.innerText="年級項格式為:第20**級!";
}
break;
//驗證專業
case 6:
text=document.getElementById("major_input").value;
var check=document.getElementById("majorCheck_label");
if (text=="") {
check.style.color="red";
check.innerText="專業項不能為空!";
}
else if (text.search(/^[\u4e00-\u9fa5]+[a-zA-Z]*$/g) !=-1) {
check.style.color="yellow";
check.innerText="專業項填寫正確!";
}
else {
check.style.color="red";
check.innerText="專業項填寫不正確!";
}
break;
//驗證班級
case 7:
text=document.getElementById("class_input").value;
var check=document.getElementById("classCheck_label");
if (text=="") {
check.style.color="red";
check.innerText="班級項不能為空!";
}
else if (text.search(/^[\u4e00-\u9fa5]+\d{4}$/) !=-1) {
check.style.color="yellow";
check.innerText="班級項填寫正確!";
}
else {
check.style.color="red";
check.innerText="班級項格式為:電信1001!";
}
break;
//驗證電話
case 8:
text=document.getElementById("phone_input").value;
var check=document.getElementById("phoneCheck_label");
if (text=="") {
break;
}
else if (text.search(/^(\+86)?1\d{10}$/) !=-1) {
check.style.color="yellow";
check.innerText="手機項填寫正確!";
}
else {
check.style.color="red";
check.innerText="手機項格式錯誤!";
}
break;
}
}
利用正則表達式進行注冊信息格式驗證是非常重要的一個知識點,希望這個小練習能夠幫助你更快地掌握!
我們下期再見!
END
文案編輯|云端學長
文案配圖|云端學長
內容由:云端源想分享
正則表達式是一種用來匹配字符串的強有力的武器
它的設計思想是用一種描述性的語言定義一個規則,凡是符合規則的字符串,我們就認為它“匹配”了,否則,該字符串就是不合法的
根據正則表達式語法規則,大部分字符僅能夠描述自身,這些字符被稱為普通字符,如所有的字母、數字等。
元字符就是擁有特動功能的特殊字符,大部分需要加反斜杠進行標識,以便于普通字符進行區別,而少數元字符,需要加反斜杠,以便轉譯為普通字符使用。JavaScript 正則表達式支持的元字符如表所示。
在 JavaScript中,正則表達式也是對象,構建正則表達式有兩種方式:
const re=/\d+/g;
const re=new RegExp("\\d+","g");
const rul="\\d+"
const re1=new RegExp(rul,"g");
使用構建函數創建,第一個參數可以是一個變量,遇到特殊字符\需要使用\進行轉義
表示字符的方法有多種,除了可以直接使用字符本身外,還可以使用 ASCII 編碼或者 Unicode 編碼來表示。
下面使用 ASCII 編碼定義正則表達式直接量。
var r=/\x61/;var s="JavaScript";var a=s.match(s);
由于字母 a 的 ASCII 編碼為 97,被轉換為十六進制數值后為 61,因此如果要匹配字符 a,就應該在前面添加“\x”前綴,以提示它為 ASCII 編碼。
除了十六進制外,還可以直接使用八進制數值表示字符。
var r=/1/;var s="JavaScript";var a=s.match(r);
使用十六進制需要添加“\x”前綴,主要是為了避免語義混淆,而八進制則不需要添加前綴。
ASCII 編碼只能夠匹配有限的單字節字符,使用 Unicode 編碼可以表示雙字節字符。Unicode 編碼方式:“\u”前綴加上 4 位十六進制值。
var r="/\u0061/";var s="JavaScript";var a=s.match(s);
在 RegExp() 構造函數中使用元字符時,應使用雙斜杠。
var r=new RegExp("\u0061");
RegExp() 構造函數的參數只接受字符串,而不是字符模式。在字符串中,任何字符加反斜杠還表示字符本身,如字符串“\u”就被解釋為 u 本身,所以對于“\u0061”字符串來說,在轉換為字符模式時,就被解釋為“u0061”,而不是“\u0061”,此時反斜杠就失去轉義功能。解決方法:在字符 u 前面加雙反斜杠。
常見的校驗規則如下:
規則 | 描述 |
\ | 轉義 |
^ | 匹配輸入的開始 |
$ | 匹配輸入的結束 |
* | 匹配前一個表達式 0 次或多次 |
+ | 匹配前面一個表達式 1 次或者多次。等價于 {1,} |
? | 匹配前面一個表達式 0 次或者 1 次。等價于{0,1} |
. | 默認匹配除換行符之外的任何單個字符 |
x(?=y) | 匹配'x'僅僅當'x'后面跟著'y'。這種叫做先行斷言 |
(?<=y)x | 匹配'x'僅當'x'前面是'y'.這種叫做后行斷言 |
x(?!y) | 僅僅當'x'后面不跟著'y'時匹配'x',這被稱為正向否定查找 |
(?<!y)x | 僅僅當'x'前面不是'y'時匹配'x',這被稱為反向否定查找 |
x|y | 匹配‘x’或者‘y’ |
{n} | n 是一個正整數,匹配了前面一個字符剛好出現了 n 次 |
{n,} | n是一個正整數,匹配前一個字符至少出現了n次 |
{n,m} | n 和 m 都是整數。匹配前面的字符至少n次,最多m次 |
[xyz] | 一個字符集合。匹配方括號中的任意字符 |
[^xyz] | 匹配任何沒有包含在方括號中的字符 |
\b | 匹配一個詞的邊界,例如在字母和空格之間 |
\B | 匹配一個非單詞邊界 |
\d | 匹配一個數字 |
\D | 匹配一個非數字字符 |
\f | 匹配一個換頁符 |
\n | 匹配一個換行符 |
\r | 匹配一個回車符 |
\s | 匹配一個空白字符,包括空格、制表符、換頁符和換行符 |
\S | 匹配一個非空白字符 |
\w | 匹配一個單字字符(字母、數字或者下劃線) |
\W | 匹配一個非單字字符 |
標志 | 描述 |
g | 全局搜索。 |
i | 不區分大小寫搜索。 |
m | 多行搜索。 |
s | 允許 . 匹配換行符。 |
u | 使用unicode碼的模式進行匹配。 |
y | 執行“粘性(sticky)”搜索,匹配從目標字符串的當前位置開始。 |
使用方法如下:
var re=/pattern/flags;
var re=new RegExp("pattern", "flags");
在了解下正則表達式基本的之外,還可以掌握幾個正則表達式的特性:
在了解貪婪模式前,首先舉個例子:
const reg=/ab{1,3}c/
在匹配過程中,嘗試可能的順序是從多往少的方向去嘗試。首先會嘗試bbb,然后再看整個正則是否能匹配。不能匹配時,吐出一個b,即在bb的基礎上,再繼續嘗試,以此重復
如果多個貪婪量詞挨著,則深度優先搜索
const string="12345";
const regx=/(\d{1,3})(\d{1,3})/;
console.log( string.match(reg) );
//=> ["12345", "123", "45", index: 0, input: "12345"]
其中,前面的\d{1,3}匹配的是"123",后面的\d{1,3}匹配的是"45"
惰性量詞就是在貪婪量詞后面加個問號。表示盡可能少的匹配
var string="12345";
var regex=/(\d{1,3}?)(\d{1,3})/;
console.log( string.match(regex) );
//=> ["1234", "1", "234", index: 0, input: "12345"]
其中\d{1,3}?只匹配到一個字符"1",而后面的\d{1,3}匹配了"234"
分組主要是用過()進行實現,比如beyond{3},是匹配d字母3次。而(beyond){3}是匹配beyond三次
在()內使用|達到或的效果,如(abc | xxx)可以匹配abc或者xxx
反向引用,巧用$分組捕獲
let str="John Smith";
// 交換名字和姓氏
console.log(str.replace(/(john) (smith)/i, '$2, $1')) // Smith, John
正則表達式常被用于某些方法,我們可以分成兩類:
方法 | 描述 |
exec | 一個在字符串中執行查找匹配的RegExp方法,它返回一個數組(未匹配到則返回 null)。 |
test | 一個在字符串中測試是否匹配的RegExp方法,它返回 true 或 false。 |
match | 一個在字符串中執行查找匹配的String方法,它返回一個數組,在未匹配到時會返回 null。 |
matchAll | 一個在字符串中執行查找所有匹配的String方法,它返回一個迭代器(iterator)。 |
search | 一個在字符串中測試匹配的String方法,它返回匹配到的位置索引,或者在失敗時返回-1。 |
replace | 一個在字符串中執行查找匹配的String方法,并且使用替換字符串替換掉匹配到的子字符串。 |
split | 一個使用正則表達式或者一個固定字符串分隔一個字符串,并將分隔后的子字符串存儲到數組中的 String 方法。 |
str.match(regexp) 方法在字符串 str 中找到匹配 regexp 的字符
如果 regexp 不帶有 g 標記,則它以數組的形式返回第一個匹配項,其中包含分組和屬性 index(匹配項的位置)、input(輸入字符串,等于 str)
let str="I love JavaScript";
let result=str.match(/Java(Script)/);
console.log( result[0] ); // JavaScript(完全匹配)
console.log( result[1] ); // Script(第一個分組)
console.log( result.length ); // 2
// 其他信息:
console.log( result.index ); // 7(匹配位置)
console.log( result.input ); // I love JavaScript(源字符串)
如果 regexp 帶有 g 標記,則它將所有匹配項的數組作為字符串返回,而不包含分組和其他詳細信息
let str="I love JavaScript";
let result=str.match(/Java(Script)/g);
console.log( result[0] ); // JavaScript
console.log( result.length ); // 1
如果沒有匹配項,則無論是否帶有標記 g ,都將返回 null
let str="I love JavaScript";
let result=str.match(/HTML/);
console.log(result); // null
返回一個包含所有匹配正則表達式的結果及分組捕獲組的迭代器
const regexp=/t(e)(st(\d?))/g;
const str='test1test2';
const array=[...str.matchAll(regexp)];
console.log(array[0]);
// expected output: Array ["test1", "e", "st1", "1"]
console.log(array[1]);
// expected output: Array ["test2", "e", "st2", "2"]
返回第一個匹配項的位置,如果未找到,則返回 -1
let str="A drop of ink may make a million think";
console.log( str.search( /ink/i ) ); // 10(第一個匹配位置)
這里需要注意的是,search 僅查找第一個匹配項
替換與正則表達式匹配的子串,并返回替換后的字符串。在不設置全局匹配g的時候,只替換第一個匹配成功的字符串片段
const reg1=/javascript/i;
const reg2=/javascript/ig;
console.log('hello Javascript Javascript Javascript'.replace(reg1,'js'));
//hello js Javascript Javascript
console.log('hello Javascript Javascript Javascript'.replace(reg2,'js'));
//hello js js js
使用正則表達式(或子字符串)作為分隔符來分割字符串
console.log('12, 34, 56'.split(/,\s*/)) // 數組 ['12', '34', '56']
regexp.exec(str) 方法返回字符串 str 中的 regexp 匹配項,與以前的方法不同,它是在正則表達式而不是字符串上調用的
根據正則表達式是否帶有標志 g,它的行為有所不同
如果沒有 g,那么 regexp.exec(str) 返回的第一個匹配與 str.match(regexp) 完全相同
如果有標記 g,調用 regexp.exec(str) 會返回第一個匹配項,并將緊隨其后的位置保存在屬性regexp.lastIndex 中。 下一次同樣的調用會從位置 regexp.lastIndex 開始搜索,返回下一個匹配項,并將其后的位置保存在 regexp.lastIndex 中
let str='More about JavaScript at https://javascript.info';
let regexp=/javascript/ig;
let result;
while (result=regexp.exec(str)) {
console.log( `Found ${result[0]} at position ${result.index}` );
// Found JavaScript at position 11
// Found javascript at position 33
}
查找匹配項,然后返回 true/false 表示是否存在
let str="I love JavaScript";
// 這兩個測試相同
console.log( /love/i.test(str) ); // true
通過上面的學習,我們對正則表達式有了一定的了解
下面再來看看正則表達式一些案例場景:
驗證QQ合法性(5~15位、全是數字、不以0開頭):
const reg=/^[1-9][0-9]{4,14}$/
const isvalid=patrn.exec(s)
校驗用戶賬號合法性(只能輸入5-20個以字母開頭、可帶數字、“_”、“.”的字串):
var patrn=/^[a-zA-Z]{1}([a-zA-Z0-9]|[._]){4,19}$/;
const isvalid=patrn.exec(s)
將url參數解析為對象
const protocol='(?<protocol>https?:)';
const host='(?<host>(?<hostname>[^/#?:]+)(?::(?<port>\\d+))?)';
const path='(?<pathname>(?:\\/[^/#?]+)*\\/?)';
const search='(?<search>(?:\\?[^#]*)?)';
const hash='(?<hash>(?:#.*)?)';
const reg=new RegExp(`^${protocol}\/\/${host}${path}${search}${hash}$`);
function execURL(url){
const result=reg.exec(url);
if(result){
result.groups.port=result.groups.port || '';
return result.groups;
}
return {
protocol:'',host:'',hostname:'',port:'',
pathname:'',search:'',hash:'',
};
}
console.log(execURL('https://localhost:8080/?a=b#xxxx'));
protocol: "https:"
host: "localhost:8080"
hostname: "localhost"
port: "8080"
pathname: "/"
search: "?a=b"
hash: "#xxxx"
再將上面的search和hash進行解析
function execUrlParams(str){
str=str.replace(/^[#?&]/,'');
const result={};
if(!str){ //如果正則可能配到空字符串,極有可能造成死循環,判斷很重要
return result;
}
const reg=/(?:^|&)([^&=]*)=?([^&]*?)(?=&|$)/y
let exec=reg.exec(str);
while(exec){
result[exec[1]]=exec[2];
exec=reg.exec(str);
}
return result;
}
console.log(execUrlParams('#'));// {}
console.log(execUrlParams('##'));//{'#':''}
console.log(execUrlParams('?q=3606&src=srp')); //{q: "3606", src: "srp"}
console.log(execUrlParams('test=a=b=c&&==&a='));//{test: "a=b=c", "": "=", a: ""}
1. dotAll模式(s選項)
這個特性已經在ECMAScript 2018正式發布了。
默認情況下,.可以匹配任意字符,除了換行符:
/foo.bar/u.test('foo\nbar'); // false
另外,.不能匹配Unicode字符,需要使用u選項啟用Unicode模式才行。
ES2018引入了dotAll模式,通過s選項可以啟用,這樣,.就可以匹配換行符了。
/foo.bar/su.test('foo\nbar'); // true
2. Lookbehind斷言
這個特性已經在ECMAScript 2018正式發布了。
ECMAScript目前僅支持lookahead斷言。
下面示例是Positive lookahead,匹配字符串“42 dollars”中緊跟著是”dollars”的數字:
const pattern=/\d+(?=dollars)/u;
const result=pattern.exec('42 dollars');
console.log(result[0]); // 打印42
下面示例是Negative lookahead,匹配字符串“42 pesos”中緊跟著的不是”dollars”的數字:
const pattern=/\d+(?! dollars)/u;
const result=pattern.exec('42 pesos');
console.log(result[0]); // 打印42
ES2018添加了lookbehind斷言。
下面示例是Positive lookbehind,匹配字符串“”中前面是”$”的數字:
const pattern=/(?<=\$)\d+/u;
const result=pattern.exec('$42');
console.log(result[0]); // 打印42
下面示例是Negative lookbehind,匹配字符串“”中前面不是是”$”的數字:
const pattern=/(?<!\$)\d+/u;
const result=pattern.exec('42');
console.log(result[0]); // 打印42
Fundebug專注于網頁、微信小程序、微信小游戲,支付寶小程序,React Native,Node.js和Java線上BUG實時監控,歡迎免費試用
3. Named capture groups
這個特性已經在ECMAScript 2018正式發布了。
目前,正則表達式中小括號匹配的分組是通過數字編號的:
const pattern=/(\d{4})-(\d{2})-(\d{2})/u;
const result=pattern.exec('2017-01-25');
console.log(result[0]); // 打印"2017-01-25"
console.log(result[1]); // 打印"2017"
console.log(result[2]); // 打印"01"
console.log(result[3]); // 打印"25"
這樣很方便,但是可讀性很差,且不易維護。一旦正則表達式中小括號的順序有變化時,我們就需要更新對應的數字編號。
ES2018添加named capture groups, 可以指定小括號中匹配內容的名稱,這樣可以提高代碼的可讀性,也便于維護。
const pattern=/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/u;
const result=pattern.exec('2017-01-25');
console.log(result.groups.year); // 打印"2017"
console.log(result.groups.month); // 打印"01"
console.log(result.groups.day); // 打印"25"
4. Unicode property escapes
這個特性已經在ECMAScript 2018正式發布了。
Unicode標準為每一個字符分配了多個屬性。比如,當你要匹配希臘語字符時,則可以搜索Script_Extensions屬性為Greek的字符。
Unicode property escapes使得我們可以使用ECMAScript正則表達式直接匹配Unicode字符的屬性:
const regexGreekSymbol=/\p{Script_Extensions=Greek}/u;
console.log(regexGreekSymbol.test('π')); // 打印true
5. String.prototype.matchAll
這個特性還處在Stage 3 Draft
g和y選項通常用于匹配一個字符串,然后遍歷所有匹配的子串,包括小括號匹配的分組。String.prototype.matchAll讓這個操作變得更加簡單了。
const string='Magic hex numbers: DEADBEEF CAFE 8BADF00D';
const regex=/\b[0-9a-fA-F]+\b/g;
for (const match of string.matchAll(regex)) {
console.log(match);
}
每一個迭代所返回的match對象與regex.exec(string)所返回的結果相同:
// Iteration 1:
[
'DEADBEEF',
index: 19,
input: 'Magic hex numbers: DEADBEEF CAFE 8BADF00D'
]
// Iteration 2:
[
'CAFE',
index: 28,
input: 'Magic hex numbers: DEADBEEF CAFE 8BADF00D'
]
// Iteration 3:
[
'8BADF00D',
index: 33,
input: 'Magic hex numbers: DEADBEEF CAFE 8BADF00D'
]
注意,這個特性還處在Stage 3 Draft,因此還存在變化的可能性,示例代碼是根據最新的提案寫的。另外,瀏覽器也還沒有支持這個特性。String.prototype.matchAll最快可以被加入到ECMAScript 2019中。
6. 規范RegExp遺留特性
這個提案還處在Stage 3 Draft
這個提案規范了RegExp的遺留特性,比如RegExp.prototype.compile方法以及它的靜態屬性從RegExp.到RegExp.。雖然這些特性已經棄用(deprecated)了,但是為了兼容性我們不能將他們去。因此,規范這些RegExp遺留特性是最好的方法。因此,這個提案有助于保證兼容性。
/**
* @param {string} path
* @returns {Boolean}
*/
export function isExternal(path) {
return /^(https?:|mailto:|tel:)/.test(path)
}
/**
* @param {string} str
* @returns {Boolean}
*/
export function validUsername(str) {
const valid_map=['admin', 'editor']
return valid_map.indexOf(str.trim()) >=0
}
/**
* @param {string} url
* @returns {Boolean}
*/
export function validURL(url) {
const reg=/^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/
return reg.test(url)
}
/**
* @param {string} str
* @returns {Boolean}
*/
export function validLowerCase(str) {
const reg=/^[a-z]+$/
return reg.test(str)
}
/**
* @param {string} str
* @returns {Boolean}
*/
export function validUpperCase(str) {
const reg=/^[A-Z]+$/
return reg.test(str)
}
/**
* @param {string} str
* @returns {Boolean}
*/
export function validAlphabets(str) {
const reg=/^[A-Za-z]+$/
return reg.test(str)
}
/**
* @param {string} email
* @returns {Boolean}
*/
export function validEmail(email) {
const reg=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
return reg.test(email)
}
/**
* @param {string} str
* @returns {Boolean}
*/
export function isString(str) {
if (typeof str==='string' || str instanceof String) {
return true
}
return false
}
/**
* @param {Array} arg
* @returns {Boolean}
*/
export function isArray(arg) {
if (typeof Array.isArray==='undefined') {
return Object.prototype.toString.call(arg)==='[object Array]'
}
return Array.isArray(arg)
}
TS版
/**
* @param {string} path
* @returns {Boolean}
*/
export function isExternal(path) {
return /^(https?:|mailto:|tel:)/.test(path);
}
/**
* @param {string} str
* @returns {Boolean}
*/
export function validUsername(str) {
const valid_map=['admin', 'editor'];
return valid_map.indexOf(str.trim()) >=0;
}
/**
* @param {string} url
* @returns {Boolean}
*/
export function validURL(url) {
const reg=/^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/;
return reg.test(url);
}
/**
* @param {string} str
* @returns {Boolean}
*/
export function validLowerCase(str) {
const reg=/^[a-z]+$/;
return reg.test(str);
}
/**
* @param {string} str
* @returns {Boolean}
*/
export function validUpperCase(str) {
const reg=/^[A-Z]+$/;
return reg.test(str);
}
/**
* @param {string} str
* @returns {Boolean}
*/
export function validAlphabets(str) {
const reg=/^[A-Za-z]+$/;
return reg.test(str);
}
/**
* @param {string} email
* @returns {Boolean}
*/
export function validEmail(email) {
const reg=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return reg.test(email);
}
/**
* @param {string} phone
* @returns {Boolean}
*/
export function validPhone(phone) {
const reg=/^1[3-9][0-9]{9}$/;
return reg.test(phone);
}
/**
* @param {string} str
* @returns {Boolean}
*/
export function isString(str) {
if (typeof str==='string' || str instanceof String) {
return true;
}
return false;
}
/**
* @param {Array} arg
* @returns {Boolean}
*/
export function isArray(arg) {
if (typeof Array.isArray==='undefined') {
return Object.prototype.toString.call(arg)==='[object Array]';
}
return Array.isArray(arg);
}
// [修改]-新增-開始
/**
* 英文驗證
* @param min
* @param max
* @param value
*/
export function english(value: string, min=6, max=12): boolean {
return new RegExp('^[a-z|A-Z]{' + min + ',' + max + '}$').test(value);
}
/**
* 中文驗證
* @param min
* @param max
* @param value
*/
export function chinese(value: string, min=2, max=12): boolean {
return new RegExp('^[\u4e00-\u9fa5]{' + min + ',' + max + '}$').test(value);
}
/**
* 非中文
* @param value 內容
* @returns boolean
*/
export function notChinese(value: string): boolean {
return !/[\u4e00-\u9fa5]/.test(value);
}
/**
* 必需數字
* @param min
* @param max
* @param value
*/
export function number(value: string, min=1, max=20): boolean {
return new RegExp('^d{' + min + ',' + max + '}$').test(value);
}
/**
* 必需小數點最大值
* @param min
* @param max
* @param value
*/
export function precision(value: string, max=8, precision=8): boolean {
return new RegExp(
'(^[0-9]{1,' + max + '}$)|(^[0-9]{1,' + max + '}[.]{1}[0-9]{1,' + precision + '}$)',
).test(value);
}
/**
* 復雜密碼驗證
* @param value
*/
export function pwd(value: string): boolean {
if (value && value.length > 15) {
const en=/[a-z]/.test(value);
const num=/[0-9]/.test(value);
const daxie=/[A-Z]/.test(value);
const teshu=/[~!@#$%^&*()_+=-\[\]\\,.\/;':{}]/.test(value);
return en && num && daxie && teshu;
}
return false;
}
// [修改]-新增-結束
給大家分享我收集整理的各種學習資料,前端小白交學習流程,入門教程等回答-下面是學習資料參考。
前端學習交流、自學、學習資料等推薦 - 知乎
*請認真填寫需求信息,我們會在24小時內與您取得聯系。