正則表達(dá)式一般用于字符串匹配,字符串查找和字符串替換。別小看它的作用,在工作學(xué)習(xí)中靈活運(yùn)用正則表達(dá)式處理字符串能夠大幅度提高效率,編程的快樂(lè)來(lái)得就是這么簡(jiǎn)單。
下面將由淺入深講解正則表達(dá)式的使用。
package test;
public class Test01 {
public static void main(String[] args) {
//字符串a(chǎn)bc匹配正則表達(dá)式"...", 其中"."表示一個(gè)字符
//"..."表示三個(gè)字符
System.out.println("abc".matches("..."));
System.out.println("abcd".matches("..."));
}
}
輸出結(jié)果:
true
false
String類中有個(gè)matches(String regex)方法, 返回值為布爾類型,用于告訴這個(gè)字符串是否匹配給定的正則表達(dá)式。
在本例中我們給出的正則表達(dá)式為...,其中每個(gè).表示一個(gè)字符,整個(gè)正則表達(dá)式的意思是三個(gè)字符,顯然當(dāng)匹配abc的時(shí)候結(jié)果為true,匹配abcd時(shí)結(jié)果為false。
在java.util.regex包下有兩個(gè)用于正則表達(dá)式的類, 一個(gè)是Matcher,另一個(gè)Pattern。
Java官方文檔中給出對(duì)這兩個(gè)類的典型用法,代碼如下:
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之間的任何一個(gè)字符, {3}表示3個(gè)字符, 意思是匹配一個(gè)長(zhǎng)度為3, 并且每個(gè)字符屬于a~z的字符串
Pattern p=Pattern.compile("[a-z]{3}");
Matcher m1=p.matcher("abc");
System.out.println(m2.matches());
}
}
輸出結(jié)果:true
Pattern可以理解為一個(gè)模式,字符串需要與某種模式進(jìn)行匹配。 比如Test02中, 我們定義的模式是一個(gè)長(zhǎng)度為3的字符串, 其中每個(gè)字符必須是a~z中的一個(gè)。
我們看到創(chuàng)建Pattern對(duì)象時(shí)調(diào)用的是Pattern類中的compile方法,也就是說(shuō)對(duì)我們傳入的正則表達(dá)式編譯后得到一個(gè)模式對(duì)象。 而這個(gè)經(jīng)過(guò)編譯后模式對(duì)象,,會(huì)使得正則表達(dá)式使用效率會(huì)大大提高,并且作為一個(gè)常量,它可以安全地供多個(gè)線程并發(fā)使用。
Matcher可以理解為模式匹配某個(gè)字符串后產(chǎn)生的結(jié)果。字符串和某個(gè)模式匹配后可能會(huì)產(chǎn)生很多個(gè)結(jié)果,這個(gè)會(huì)在后面的例子中講解。
最后當(dāng)我們調(diào)用m.matches()時(shí)就會(huì)返回完整字符串與模式匹配的結(jié)果。
上面的三行代碼可以簡(jiǎn)化為一行代碼:
System.out.println("abc".matches("[a-z]{3}"));
但是如果一個(gè)正則表達(dá)式需要被重復(fù)匹配,這種寫法效率較低。
代碼示例:
package test;
public class Test03 {
private static void p(Object o){
System.out.println(o);
}
public static void main(String[] args) {
// "X*" 代表零個(gè)或多個(gè)X
p("aaaa".matches("a*"));
p("".matches("a*"));
// "X+" 代表一個(gè)或多個(gè)X
p("aaaa".matches("a+"));
// "X?" 代表零個(gè)或一個(gè)X
p("a".matches("a?"));
// \\d A digit: [0-9], 表示數(shù)字, 但是在java中對(duì)"\\"這個(gè)符號(hào)需要使用\\進(jìn)行轉(zhuǎn)義, 所以出現(xiàn)\\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中的一個(gè)數(shù)字
p("192".matches("[0-2][0-9][0-9]"));
}
}
輸出結(jié)果:全是true。
[]用于描述一個(gè)字符的范圍, 下面是一些例子:
package test;
public class Test04 {
private static void p(Object o){
System.out.println(o);
}
public static void main(String[] args) {
//[abc]指abc中的其中一個(gè)字母
p("a".matches("[abc]"));
//[^abc]指除了abc之外的字符
p("1".matches("[^abc]"));
//a~z或A~Z的字符, 以下三個(gè)均是或的寫法
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]]"));
}
}
輸出結(jié)果:全是true。
關(guān)于\
在Java中的字符串中,如果要用到特殊字符, 必須通過(guò)在前面加\進(jìn)行轉(zhuǎn)義。
舉個(gè)例子,考慮這個(gè)字符串"老師大聲說(shuō):"同學(xué)們,快交作業(yè)!""。 如果我們沒(méi)有轉(zhuǎn)義字符,那么開(kāi)頭的雙引號(hào)的結(jié)束應(yīng)該在說(shuō):"這里,但是我們的字符串中需要用到雙引號(hào), 所以需要用轉(zhuǎn)義字符。
使用轉(zhuǎn)義字符后的字符串為"老師大聲說(shuō):\"同學(xué)們,快交作業(yè)!\"", 這樣我們的原意才能被正確識(shí)別。
同理如果我們要在字符串中使用\,也應(yīng)該在前面加一個(gè)\,所以在字符串中表示為"\"。
那么如何在正則表達(dá)式中表示要匹配\呢? 答案為"\\"。
我們分開(kāi)考慮:由于正則式中表示\同樣需要轉(zhuǎn)義, 所以前面的\表示正則表達(dá)式中的轉(zhuǎn)義字符\,后面的\表示正則表達(dá)式中\(zhòng)本身, 合起來(lái)在正則表達(dá)式中表示\。
先來(lái)看代碼示例:
package test;
public class Test05 {
private static void p(Object o){
System.out.println(o);
}
public static void main(String[] args) {
// \s{4}表示4個(gè)空白符
p(" \n\r\t".matches("\\s{4}"));
// \S表示非空白符
p("a".matches("\\S"));
// \w{3}表示數(shù)字字母和下劃線
p("a_8".matches("\\w{3}"));
p("abc888&^%".matches("[a-z]{1,3}\\d+[%^&*]+"));
// 匹配 \
p("\\".matches("\\\\"));
}
}
^在中括號(hào)內(nèi)表示取反的意思[^], 如果不在中括號(hào)里則表示字符串的開(kāi)頭。
代碼示例:
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 一個(gè)字符串的開(kāi)始
* $ The end of a line 字符串的結(jié)束
* \b A word boundary 一個(gè)單詞的邊界, 可以是空格, 換行符等
*/
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.*"));
}
}
輸出結(jié)果:
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(), 與整個(gè)字符串匹配.
p(m.matches());
//結(jié)果為false, 顯然要匹配3~5個(gè)數(shù)字會(huì)在-處匹配失敗
//然后演示find(), 先使用reset()方法把當(dāng)前位置設(shè)置為字符串的開(kāi)頭
m.reset();
p(m.find());//true 匹配123成功
p(m.find());//true 匹配34345成功
p(m.find());//true 匹配234成功
p(m.find());//false 匹配00失敗
//下面我們演示不在matches()使用reset(), 看看當(dāng)前位置的變化
m.reset();//先重置
p(m.matches());//false 匹配整個(gè)字符串失敗, 當(dāng)前位置來(lái)到-
p(m.find());// true 匹配34345成功
p(m.find());// true 匹配234成功
p(m.find());// false 匹配00始邊
p(m.find());// false 沒(méi)有東西匹配, 失敗
//演示lookingAt(), 從頭開(kāi)始找
p(m.lookingAt());//true 找到123, 成功
}
}
如果一次匹配成功的話start()用于返回匹配開(kāi)始的位置,
end()用于返回匹配結(jié)束字符的后面一個(gè)位置。
代碼示例:
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("報(bào)錯(cuò)了...");
}
p(m.lookingAt());
p("start: " + m.start() + " - end:" + m.end());
}
}
輸出結(jié)果:
true
start: 0 - end:3
true
start: 4 - end:9
true
start: 10 - end:13
false
報(bào)錯(cuò)了...
true
start: 0 - end:3
Matcher類中的一個(gè)方法group(),它能返回匹配到的字符串。
代碼示例:將字符串中的java轉(zhuǎn)換為大寫
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()方法會(huì)替換所有匹配到的字符串
}
}
輸出結(jié)果:
JAVA I love Java and you
我們要在創(chuàng)建模板模板時(shí)指定大小寫不敏感。
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"));
}
輸出結(jié)果:
JAVA I love JAVA and you
這里演示把查找到第奇數(shù)個(gè)字符串轉(zhuǎn)換為大寫,第偶數(shù)個(gè)轉(zhuǎn)換為小寫。
這里會(huì)引入Matcher類中一個(gè)強(qiáng)大的方法appendReplacement(StringBuffer sb, String replacement),它需要傳入一個(gè)StringBuffer進(jìn)行字符串拼接。
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);
}
輸出結(jié)果:
JAVA JAVA JAVA JAVA I love JAVA and you ?
先看一個(gè)示例:
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());
}
}
}
輸出結(jié)果:
005aa
856zx
1425kj
其中正則表達(dá)式"\d{3,5}[a-z]{2}"表示3~5個(gè)數(shù)字跟上兩個(gè)字母,然后打印出每個(gè)匹配到的字符串。
如果想要打印每個(gè)匹配串中的數(shù)字,如何操作呢?
分組機(jī)制可以幫助我們?cè)谡齽t表達(dá)式中進(jìn)行分組。規(guī)定使用()進(jìn)行分組,這里我們把字母和數(shù)字各分為一組"(\d{3,5})([a-z]{2})"
然后在調(diào)用m.group(int group)方法時(shí)傳入組號(hào)即可。
注意:組號(hào)從0開(kāi)始,0組代表整個(gè)正則表達(dá)式,從0之后,就是在正則表達(dá)式中從左到右每一個(gè)左括號(hào)對(duì)應(yīng)一個(gè)組。在這個(gè)表達(dá)式中第1組是數(shù)字, 第2組是字母。
public static void main(String[] args) {
Pattern p=Pattern.compile("(\\d{3,5})([a-z]{2})");//正則表達(dá)式為3~5個(gè)數(shù)字跟上兩個(gè)字母
String s="005aa-856zx-1425kj-29";
Matcher m=p.matcher(s);
while(m.find()){
p(m.group(1));
}
}
輸出結(jié)果:
005
856
1425
以上就是對(duì)于正則表達(dá)式的一個(gè)總結(jié)和使用說(shuō)明,愿正則表達(dá)式給你帶來(lái)更愉快的編程體驗(yàn)。
作者:初念初戀
原文鏈接:https://juejin.cn/post/6999944971495145502
這里是云端源想IT,幫你輕松學(xué)IT”
嗨~ 今天的你過(guò)得還好嗎?
如果你趕不上凌晨五點(diǎn)的日出
你不妨看看傍晚六點(diǎn)的夕陽(yáng)
我的意思是
你可以選擇后者
- 2023.06.30 -
說(shuō)起正則表達(dá)式大家應(yīng)該都不陌生,今天小編給大家找了一個(gè)JavaScript正則表達(dá)式的練習(xí),利用正則表達(dá)式進(jìn)行注冊(cè)信息格式驗(yàn)證,快打開(kāi)你的電腦一起來(lái)練習(xí)試試吧!
注冊(cè)信息界面如下:
需求格式要求如下,開(kāi)始練習(xí)前,大家要仔細(xì)閱讀要求哦!
格式要求:
1、學(xué)號(hào)項(xiàng)不能為空,必須為純數(shù)字,不能與數(shù)據(jù)庫(kù)中的重復(fù),正則表達(dá)式/^\d+$/g;
2、姓名項(xiàng)不能為空;
3、密碼不能為空且無(wú)空格判斷空格text.split(" ").length !=1,安全等級(jí)分為3個(gè)等級(jí):
4、確認(rèn)密碼項(xiàng)要求與密碼項(xiàng)填寫的密碼一致;
5、年級(jí)項(xiàng)不能為空,且格式必須為第20**級(jí),正則表達(dá)式text.search(/^\u7B2C{1}20\d+\u7EA7{1}$/) !=-1;
6、專業(yè)項(xiàng)不能為空,且只能以漢字開(kāi)頭,結(jié)尾可以為漢字或者字母正則表達(dá)式text.search(/^[\u4e00-\u9fa5]+[a-zA-Z]*$/g) !=-1;
7、班級(jí)項(xiàng)不能為空且格式為專業(yè)+班級(jí)即類似電信1001格,正則表達(dá)式text.search(/^[\u4e00-\u9fa5]+\d{4}$/) !=-1;
8、手機(jī)項(xiàng)可以為空,格式為(+86)1*********正則表達(dá)式text.search(/^(\+86)?1\d{10}$/) !=-1。
運(yùn)行效果:
正確格式輸入后運(yùn)行效果:
下面小編將參考代碼奉上,聽(tīng)我的!先自己試著敲代碼運(yùn)行試試,實(shí)在不會(huì)了再看答案哦!
html代碼:
<!--register-->
<div style="display:block">
<div>
<span style=" font-weight: bold;"><label>注冊(cè)</label></span>
</div>
<div>
<span class="input_span"><label class="text_label">學(xué)號(hào)</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>確認(rèn)密碼</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">年級(jí)</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**級(jí)</label></span>
</div>
<div>
<span class="input_span"><label class="text_label">專業(yè)</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">班級(jí)</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">手機(jī)</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="用戶注冊(cè)"/></span></div>
</div>
<!--end register-->
</div>
就知道有的人會(huì)直接看答案~
代碼比較長(zhǎng),大家有耐心一點(diǎn),看了答案也要自己再敲一遍哦,這樣你的體會(huì)將更深刻。
JS驗(yàn)證源代碼:
/*
* 功能: 驗(yàn)證注冊(cè)信息是否合法,在每次<input>控件失去聚焦時(shí)調(diào)用
* 參數(shù): num 控件編號(hào),指示是哪個(gè)控件觸發(fā)了該函數(shù)
* 返回值: 如果全部合法返回true,否則給予響應(yīng)的錯(cuò)誤提示并返回false
*/
function checkRegisterInfo(num) {
var text;
switch (num) {
//當(dāng)點(diǎn)擊提交按鈕時(shí)校驗(yàn)必填項(xiàng)是否為空,防止直接點(diǎn)擊提交按鈕
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("注冊(cè)失敗,打*號(hào)的項(xiàng)不能為空!");
return false;
}
else
return true;
break;
//驗(yàn)證學(xué)號(hào)
case 1:
text=document.getElementById("studentNum_input").value;
var check=document.getElementById("studentNumCheck_label");
//驗(yàn)證是否為空
if (text=="") {
check.style.color="red";
check.innerText="學(xué)號(hào)項(xiàng)不能為空!";
}
//驗(yàn)證格式
else if (text.search(/^\d+$/g)==-1) {
check.style.color="red";
check.innerText="學(xué)號(hào)應(yīng)為純數(shù)字!";
}
else {
//驗(yàn)證學(xué)號(hào)的唯一性
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) {
//服務(wù)器返回true表示該學(xué)號(hào)可用
if (xmlHttp.responseText) {
check.style.color="yellow";
check.innerText="恭喜您,該學(xué)號(hào)可用!";
}
else {
check.style.color="red";
check.innerText="您輸入的學(xué)號(hào)已存在,請(qǐng)重新輸入!";
}
}
}
}
break;
//驗(yàn)證姓名
case 2:
text=document.getElementById("name_input").value;
var check=document.getElementById("nameCheck_label");
if (text=="") {
check.style.color="red";
check.innerText="名字項(xiàng)不能為空!";
}
else {
check.style.color="yellow";
check.innerText="名字項(xiàng)填寫正確!";
}
break;
//驗(yàn)證密碼
case 3:
text=document.getElementById("passwd_rigester_input").value;
var check=document.getElementById("passwdCheck_label");
if (text=="") {
check.style.color="red";
check.innerText="密碼項(xiàng)不能為空!";
}
//密碼中只能有數(shù)字、字母和標(biāo)點(diǎn)符號(hào)
else if (text.split(" ").length !=1) {
check.style.color="red";
check.innerText="密碼中不能出現(xiàn)空格!";
}
else {
//驗(yàn)證密碼的安全級(jí)數(shù),純數(shù)字或純字母或純標(biāo)點(diǎn)為1級(jí),字母+數(shù)字為2級(jí),字母或數(shù)字任意一個(gè)+標(biāo)點(diǎn)為3級(jí)
if ((text.search(/^[a-zA-Z]+$/g) !=-1) || (text.search(/^[0-9]+$/g) !=-1)) {
check.style.color="yellow";
check.innerText="密碼安全級(jí)別為1級(jí)!";
}
else if (text.search(/^[a-zA-Z0-9]+$/g) !=-1) {
check.style.color="yellow";
check.innerText="密碼安全級(jí)別為2級(jí)!";
}
else {
check.style.color="yellow";
check.innerText="密碼安全級(jí)別為3級(jí)!";
}
}
break;
//驗(yàn)證確認(rèn)密碼
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="密碼確認(rèn)正確!";
}
break;
//驗(yàn)證年級(jí)
case 5:
text=document.getElementById("grade_input").value;
var check=document.getElementById("gradeCheck_label");
if (text=="") {
check.style.color="red";
check.innerText="年級(jí)項(xiàng)不能為空!";
}
else if (text.search(/^\u7B2C{1}20\d+\u7EA7{1}$/) !=-1) {
check.style.color="yellow";
check.innerText="年級(jí)項(xiàng)填寫正確!";
}
else {
check.style.color="red";
check.innerText="年級(jí)項(xiàng)格式為:第20**級(jí)!";
}
break;
//驗(yàn)證專業(yè)
case 6:
text=document.getElementById("major_input").value;
var check=document.getElementById("majorCheck_label");
if (text=="") {
check.style.color="red";
check.innerText="專業(yè)項(xiàng)不能為空!";
}
else if (text.search(/^[\u4e00-\u9fa5]+[a-zA-Z]*$/g) !=-1) {
check.style.color="yellow";
check.innerText="專業(yè)項(xiàng)填寫正確!";
}
else {
check.style.color="red";
check.innerText="專業(yè)項(xiàng)填寫不正確!";
}
break;
//驗(yàn)證班級(jí)
case 7:
text=document.getElementById("class_input").value;
var check=document.getElementById("classCheck_label");
if (text=="") {
check.style.color="red";
check.innerText="班級(jí)項(xiàng)不能為空!";
}
else if (text.search(/^[\u4e00-\u9fa5]+\d{4}$/) !=-1) {
check.style.color="yellow";
check.innerText="班級(jí)項(xiàng)填寫正確!";
}
else {
check.style.color="red";
check.innerText="班級(jí)項(xiàng)格式為:電信1001!";
}
break;
//驗(yàn)證電話
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="手機(jī)項(xiàng)填寫正確!";
}
else {
check.style.color="red";
check.innerText="手機(jī)項(xiàng)格式錯(cuò)誤!";
}
break;
}
}
利用正則表達(dá)式進(jìn)行注冊(cè)信息格式驗(yàn)證是非常重要的一個(gè)知識(shí)點(diǎn),希望這個(gè)小練習(xí)能夠幫助你更快地掌握!
我們下期再見(jiàn)!
END
文案編輯|云端學(xué)長(zhǎng)
文案配圖|云端學(xué)長(zhǎng)
內(nèi)容由:云端源想分享
正則表達(dá)式是一種用來(lái)匹配字符串的強(qiáng)有力的武器
它的設(shè)計(jì)思想是用一種描述性的語(yǔ)言定義一個(gè)規(guī)則,凡是符合規(guī)則的字符串,我們就認(rèn)為它“匹配”了,否則,該字符串就是不合法的
根據(jù)正則表達(dá)式語(yǔ)法規(guī)則,大部分字符僅能夠描述自身,這些字符被稱為普通字符,如所有的字母、數(shù)字等。
元字符就是擁有特動(dòng)功能的特殊字符,大部分需要加反斜杠進(jìn)行標(biāo)識(shí),以便于普通字符進(jìn)行區(qū)別,而少數(shù)元字符,需要加反斜杠,以便轉(zhuǎn)譯為普通字符使用。JavaScript 正則表達(dá)式支持的元字符如表所示。
在 JavaScript中,正則表達(dá)式也是對(duì)象,構(gòu)建正則表達(dá)式有兩種方式:
const re=/\d+/g;
const re=new RegExp("\\d+","g");
const rul="\\d+"
const re1=new RegExp(rul,"g");
使用構(gòu)建函數(shù)創(chuàng)建,第一個(gè)參數(shù)可以是一個(gè)變量,遇到特殊字符\需要使用\進(jìn)行轉(zhuǎn)義
表示字符的方法有多種,除了可以直接使用字符本身外,還可以使用 ASCII 編碼或者 Unicode 編碼來(lái)表示。
下面使用 ASCII 編碼定義正則表達(dá)式直接量。
var r=/\x61/;var s="JavaScript";var a=s.match(s);
由于字母 a 的 ASCII 編碼為 97,被轉(zhuǎn)換為十六進(jìn)制數(shù)值后為 61,因此如果要匹配字符 a,就應(yīng)該在前面添加“\x”前綴,以提示它為 ASCII 編碼。
除了十六進(jìn)制外,還可以直接使用八進(jìn)制數(shù)值表示字符。
var r=/1/;var s="JavaScript";var a=s.match(r);
使用十六進(jìn)制需要添加“\x”前綴,主要是為了避免語(yǔ)義混淆,而八進(jìn)制則不需要添加前綴。
ASCII 編碼只能夠匹配有限的單字節(jié)字符,使用 Unicode 編碼可以表示雙字節(jié)字符。Unicode 編碼方式:“\u”前綴加上 4 位十六進(jìn)制值。
var r="/\u0061/";var s="JavaScript";var a=s.match(s);
在 RegExp() 構(gòu)造函數(shù)中使用元字符時(shí),應(yīng)使用雙斜杠。
var r=new RegExp("\u0061");
RegExp() 構(gòu)造函數(shù)的參數(shù)只接受字符串,而不是字符模式。在字符串中,任何字符加反斜杠還表示字符本身,如字符串“\u”就被解釋為 u 本身,所以對(duì)于“\u0061”字符串來(lái)說(shuō),在轉(zhuǎn)換為字符模式時(shí),就被解釋為“u0061”,而不是“\u0061”,此時(shí)反斜杠就失去轉(zhuǎn)義功能。解決方法:在字符 u 前面加雙反斜杠。
常見(jiàn)的校驗(yàn)規(guī)則如下:
規(guī)則 | 描述 |
\ | 轉(zhuǎn)義 |
^ | 匹配輸入的開(kāi)始 |
$ | 匹配輸入的結(jié)束 |
* | 匹配前一個(gè)表達(dá)式 0 次或多次 |
+ | 匹配前面一個(gè)表達(dá)式 1 次或者多次。等價(jià)于 {1,} |
? | 匹配前面一個(gè)表達(dá)式 0 次或者 1 次。等價(jià)于{0,1} |
. | 默認(rèn)匹配除換行符之外的任何單個(gè)字符 |
x(?=y) | 匹配'x'僅僅當(dāng)'x'后面跟著'y'。這種叫做先行斷言 |
(?<=y)x | 匹配'x'僅當(dāng)'x'前面是'y'.這種叫做后行斷言 |
x(?!y) | 僅僅當(dāng)'x'后面不跟著'y'時(shí)匹配'x',這被稱為正向否定查找 |
(?<!y)x | 僅僅當(dāng)'x'前面不是'y'時(shí)匹配'x',這被稱為反向否定查找 |
x|y | 匹配‘x’或者‘y’ |
{n} | n 是一個(gè)正整數(shù),匹配了前面一個(gè)字符剛好出現(xiàn)了 n 次 |
{n,} | n是一個(gè)正整數(shù),匹配前一個(gè)字符至少出現(xiàn)了n次 |
{n,m} | n 和 m 都是整數(shù)。匹配前面的字符至少n次,最多m次 |
[xyz] | 一個(gè)字符集合。匹配方括號(hào)中的任意字符 |
[^xyz] | 匹配任何沒(méi)有包含在方括號(hào)中的字符 |
\b | 匹配一個(gè)詞的邊界,例如在字母和空格之間 |
\B | 匹配一個(gè)非單詞邊界 |
\d | 匹配一個(gè)數(shù)字 |
\D | 匹配一個(gè)非數(shù)字字符 |
\f | 匹配一個(gè)換頁(yè)符 |
\n | 匹配一個(gè)換行符 |
\r | 匹配一個(gè)回車符 |
\s | 匹配一個(gè)空白字符,包括空格、制表符、換頁(yè)符和換行符 |
\S | 匹配一個(gè)非空白字符 |
\w | 匹配一個(gè)單字字符(字母、數(shù)字或者下劃線) |
\W | 匹配一個(gè)非單字字符 |
標(biāo)志 | 描述 |
g | 全局搜索。 |
i | 不區(qū)分大小寫搜索。 |
m | 多行搜索。 |
s | 允許 . 匹配換行符。 |
u | 使用unicode碼的模式進(jìn)行匹配。 |
y | 執(zhí)行“粘性(sticky)”搜索,匹配從目標(biāo)字符串的當(dāng)前位置開(kāi)始。 |
使用方法如下:
var re=/pattern/flags;
var re=new RegExp("pattern", "flags");
在了解下正則表達(dá)式基本的之外,還可以掌握幾個(gè)正則表達(dá)式的特性:
在了解貪婪模式前,首先舉個(gè)例子:
const reg=/ab{1,3}c/
在匹配過(guò)程中,嘗試可能的順序是從多往少的方向去嘗試。首先會(huì)嘗試bbb,然后再看整個(gè)正則是否能匹配。不能匹配時(shí),吐出一個(gè)b,即在bb的基礎(chǔ)上,再繼續(xù)嘗試,以此重復(fù)
如果多個(gè)貪婪量詞挨著,則深度優(yōu)先搜索
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"
惰性量詞就是在貪婪量詞后面加個(gè)問(wèn)號(hào)。表示盡可能少的匹配
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}?只匹配到一個(gè)字符"1",而后面的\d{1,3}匹配了"234"
分組主要是用過(guò)()進(jìn)行實(shí)現(xiàn),比如beyond{3},是匹配d字母3次。而(beyond){3}是匹配beyond三次
在()內(nèi)使用|達(dá)到或的效果,如(abc | xxx)可以匹配abc或者xxx
反向引用,巧用$分組捕獲
let str="John Smith";
// 交換名字和姓氏
console.log(str.replace(/(john) (smith)/i, '$2, $1')) // Smith, John
正則表達(dá)式常被用于某些方法,我們可以分成兩類:
方法 | 描述 |
exec | 一個(gè)在字符串中執(zhí)行查找匹配的RegExp方法,它返回一個(gè)數(shù)組(未匹配到則返回 null)。 |
test | 一個(gè)在字符串中測(cè)試是否匹配的RegExp方法,它返回 true 或 false。 |
match | 一個(gè)在字符串中執(zhí)行查找匹配的String方法,它返回一個(gè)數(shù)組,在未匹配到時(shí)會(huì)返回 null。 |
matchAll | 一個(gè)在字符串中執(zhí)行查找所有匹配的String方法,它返回一個(gè)迭代器(iterator)。 |
search | 一個(gè)在字符串中測(cè)試匹配的String方法,它返回匹配到的位置索引,或者在失敗時(shí)返回-1。 |
replace | 一個(gè)在字符串中執(zhí)行查找匹配的String方法,并且使用替換字符串替換掉匹配到的子字符串。 |
split | 一個(gè)使用正則表達(dá)式或者一個(gè)固定字符串分隔一個(gè)字符串,并將分隔后的子字符串存儲(chǔ)到數(shù)組中的 String 方法。 |
str.match(regexp) 方法在字符串 str 中找到匹配 regexp 的字符
如果 regexp 不帶有 g 標(biāo)記,則它以數(shù)組的形式返回第一個(gè)匹配項(xiàng),其中包含分組和屬性 index(匹配項(xiàng)的位置)、input(輸入字符串,等于 str)
let str="I love JavaScript";
let result=str.match(/Java(Script)/);
console.log( result[0] ); // JavaScript(完全匹配)
console.log( result[1] ); // Script(第一個(gè)分組)
console.log( result.length ); // 2
// 其他信息:
console.log( result.index ); // 7(匹配位置)
console.log( result.input ); // I love JavaScript(源字符串)
如果 regexp 帶有 g 標(biāo)記,則它將所有匹配項(xiàng)的數(shù)組作為字符串返回,而不包含分組和其他詳細(xì)信息
let str="I love JavaScript";
let result=str.match(/Java(Script)/g);
console.log( result[0] ); // JavaScript
console.log( result.length ); // 1
如果沒(méi)有匹配項(xiàng),則無(wú)論是否帶有標(biāo)記 g ,都將返回 null
let str="I love JavaScript";
let result=str.match(/HTML/);
console.log(result); // null
返回一個(gè)包含所有匹配正則表達(dá)式的結(jié)果及分組捕獲組的迭代器
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"]
返回第一個(gè)匹配項(xiàng)的位置,如果未找到,則返回 -1
let str="A drop of ink may make a million think";
console.log( str.search( /ink/i ) ); // 10(第一個(gè)匹配位置)
這里需要注意的是,search 僅查找第一個(gè)匹配項(xiàng)
替換與正則表達(dá)式匹配的子串,并返回替換后的字符串。在不設(shè)置全局匹配g的時(shí)候,只替換第一個(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
使用正則表達(dá)式(或子字符串)作為分隔符來(lái)分割字符串
console.log('12, 34, 56'.split(/,\s*/)) // 數(shù)組 ['12', '34', '56']
regexp.exec(str) 方法返回字符串 str 中的 regexp 匹配項(xiàng),與以前的方法不同,它是在正則表達(dá)式而不是字符串上調(diào)用的
根據(jù)正則表達(dá)式是否帶有標(biāo)志 g,它的行為有所不同
如果沒(méi)有 g,那么 regexp.exec(str) 返回的第一個(gè)匹配與 str.match(regexp) 完全相同
如果有標(biāo)記 g,調(diào)用 regexp.exec(str) 會(huì)返回第一個(gè)匹配項(xiàng),并將緊隨其后的位置保存在屬性regexp.lastIndex 中。 下一次同樣的調(diào)用會(huì)從位置 regexp.lastIndex 開(kāi)始搜索,返回下一個(gè)匹配項(xiàng),并將其后的位置保存在 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
}
查找匹配項(xiàng),然后返回 true/false 表示是否存在
let str="I love JavaScript";
// 這兩個(gè)測(cè)試相同
console.log( /love/i.test(str) ); // true
通過(guò)上面的學(xué)習(xí),我們對(duì)正則表達(dá)式有了一定的了解
下面再來(lái)看看正則表達(dá)式一些案例場(chǎng)景:
驗(yàn)證QQ合法性(5~15位、全是數(shù)字、不以0開(kāi)頭):
const reg=/^[1-9][0-9]{4,14}$/
const isvalid=patrn.exec(s)
校驗(yàn)用戶賬號(hào)合法性(只能輸入5-20個(gè)以字母開(kāi)頭、可帶數(shù)字、“_”、“.”的字串):
var patrn=/^[a-zA-Z]{1}([a-zA-Z0-9]|[._]){4,19}$/;
const isvalid=patrn.exec(s)
將url參數(shù)解析為對(duì)象
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進(jìn)行解析
function execUrlParams(str){
str=str.replace(/^[#?&]/,'');
const result={};
if(!str){ //如果正則可能配到空字符串,極有可能造成死循環(huán),判斷很重要
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選項(xiàng))
這個(gè)特性已經(jīng)在ECMAScript 2018正式發(fā)布了。
默認(rèn)情況下,.可以匹配任意字符,除了換行符:
/foo.bar/u.test('foo\nbar'); // false
另外,.不能匹配Unicode字符,需要使用u選項(xiàng)啟用Unicode模式才行。
ES2018引入了dotAll模式,通過(guò)s選項(xiàng)可以啟用,這樣,.就可以匹配換行符了。
/foo.bar/su.test('foo\nbar'); // true
2. Lookbehind斷言
這個(gè)特性已經(jīng)在ECMAScript 2018正式發(fā)布了。
ECMAScript目前僅支持lookahead斷言。
下面示例是Positive lookahead,匹配字符串“42 dollars”中緊跟著是”dollars”的數(shù)字:
const pattern=/\d+(?=dollars)/u;
const result=pattern.exec('42 dollars');
console.log(result[0]); // 打印42
下面示例是Negative lookahead,匹配字符串“42 pesos”中緊跟著的不是”dollars”的數(shù)字:
const pattern=/\d+(?! dollars)/u;
const result=pattern.exec('42 pesos');
console.log(result[0]); // 打印42
ES2018添加了lookbehind斷言。
下面示例是Positive lookbehind,匹配字符串“”中前面是”$”的數(shù)字:
const pattern=/(?<=\$)\d+/u;
const result=pattern.exec('$42');
console.log(result[0]); // 打印42
下面示例是Negative lookbehind,匹配字符串“”中前面不是是”$”的數(shù)字:
const pattern=/(?<!\$)\d+/u;
const result=pattern.exec('42');
console.log(result[0]); // 打印42
Fundebug專注于網(wǎng)頁(yè)、微信小程序、微信小游戲,支付寶小程序,React Native,Node.js和Java線上BUG實(shí)時(shí)監(jiān)控,歡迎免費(fèi)試用
3. Named capture groups
這個(gè)特性已經(jīng)在ECMAScript 2018正式發(fā)布了。
目前,正則表達(dá)式中小括號(hào)匹配的分組是通過(guò)數(shù)字編號(hào)的:
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"
這樣很方便,但是可讀性很差,且不易維護(hù)。一旦正則表達(dá)式中小括號(hào)的順序有變化時(shí),我們就需要更新對(duì)應(yīng)的數(shù)字編號(hào)。
ES2018添加named capture groups, 可以指定小括號(hào)中匹配內(nèi)容的名稱,這樣可以提高代碼的可讀性,也便于維護(hù)。
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
這個(gè)特性已經(jīng)在ECMAScript 2018正式發(fā)布了。
Unicode標(biāo)準(zhǔn)為每一個(gè)字符分配了多個(gè)屬性。比如,當(dāng)你要匹配希臘語(yǔ)字符時(shí),則可以搜索Script_Extensions屬性為Greek的字符。
Unicode property escapes使得我們可以使用ECMAScript正則表達(dá)式直接匹配Unicode字符的屬性:
const regexGreekSymbol=/\p{Script_Extensions=Greek}/u;
console.log(regexGreekSymbol.test('π')); // 打印true
5. String.prototype.matchAll
這個(gè)特性還處在Stage 3 Draft
g和y選項(xiàng)通常用于匹配一個(gè)字符串,然后遍歷所有匹配的子串,包括小括號(hào)匹配的分組。String.prototype.matchAll讓這個(gè)操作變得更加簡(jiǎn)單了。
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);
}
每一個(gè)迭代所返回的match對(duì)象與regex.exec(string)所返回的結(jié)果相同:
// 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'
]
注意,這個(gè)特性還處在Stage 3 Draft,因此還存在變化的可能性,示例代碼是根據(jù)最新的提案寫的。另外,瀏覽器也還沒(méi)有支持這個(gè)特性。String.prototype.matchAll最快可以被加入到ECMAScript 2019中。
6. 規(guī)范RegExp遺留特性
這個(gè)提案還處在Stage 3 Draft
這個(gè)提案規(guī)范了RegExp的遺留特性,比如RegExp.prototype.compile方法以及它的靜態(tài)屬性從RegExp.到RegExp.。雖然這些特性已經(jīng)棄用(deprecated)了,但是為了兼容性我們不能將他們?nèi)ァR虼耍?guī)范這些RegExp遺留特性是最好的方法。因此,這個(gè)提案有助于保證兼容性。
/**
* @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);
}
// [修改]-新增-開(kāi)始
/**
* 英文驗(yàn)證
* @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);
}
/**
* 中文驗(yàn)證
* @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 內(nèi)容
* @returns boolean
*/
export function notChinese(value: string): boolean {
return !/[\u4e00-\u9fa5]/.test(value);
}
/**
* 必需數(shù)字
* @param min
* @param max
* @param value
*/
export function number(value: string, min=1, max=20): boolean {
return new RegExp('^d{' + min + ',' + max + '}$').test(value);
}
/**
* 必需小數(shù)點(diǎn)最大值
* @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);
}
/**
* 復(fù)雜密碼驗(yàn)證
* @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;
}
// [修改]-新增-結(jié)束
給大家分享我收集整理的各種學(xué)習(xí)資料,前端小白交學(xué)習(xí)流程,入門教程等回答-下面是學(xué)習(xí)資料參考。
前端學(xué)習(xí)交流、自學(xué)、學(xué)習(xí)資料等推薦 - 知乎
*請(qǐng)認(rèn)真填寫需求信息,我們會(huì)在24小時(shí)內(nèi)與您取得聯(lián)系。