js regular test exec match replace split search assertion

Foreword

Regular expression is mainly used to verify the client's input data. After the user fill in the form click the button, the form will be sent to the server, usually further processed with PHP, ASP.NET and other server scripts on the server side. Because the client validation, can save a lot of system resources on the server side and provide a better user experience.

Regex (regular expression) is an object-character mode description. ECMAScript RegExp class of a regular expression. The string and RegExp are defined using a regular expression pattern matching and function powerful text search and replace.

Way to create regular expressions

  1. Create literal var re = / a /
  2. Constructor creates var re = new RegExp (regular matches, modifier);

Modifiers:

  • case-insensitive matching i
  • g to perform a global match
  • m perform multi-line matching
var reg=/a/g;  //字面量创建
var reg=new RegExp("a","g");//构造函数创建
console.dir(reg);
// reg.flags  就是修饰符
// reg.source  就是正则匹配内容

Print out the results are as follows, wherein:

  • reg.flags is a modifier
  • reg.source is regular matches
    Regular Expressions

Regular expression metacharacters

Regular expressions commonly used special characters:

symbol meaning
^ Matching the start position, represented antisense ^ in []
$ End position matching
. Match any one character can be any, in []. Character.
Matches the preceding character zero or one time, {0,1}; all the greedy match, plus a behind is? Non-greedy match , the scenario is: there is something else after the current need for intermediate contents match, the first matching the smallest
+ Matches the preceding character one or more times, at least once {1}
* Matches the preceding character n times, can be seen as a wildcard, {0}
() Group, matched parentheses placed into a group, the first group is $ 1, $ 2 is the second group, the third group is $ 3 ..., using match (), if not globally , in addition to the element returns to find, but also the return of a group of elements
{n} Matches the preceding character n times; and when n is 0, meaning that matches a null character, i.e., ""
{n,} Matches the preceding character at least n times
{n,m} Matches the preceding character at least n times m times the maximum allowed, the default is greedy match , to match the maximum
[ ] [] Matches the contents inside a character may optionally be used 0-9 az AZ
[ ^ ] The first use [] in ^, ^ said that apart behind the characters meet; ^ If [] is not the first one, it means that the character ^
| Alternatively, can be used with a character or another character, if | end have no content that matches a null character
\ Commonly used as an escape character

Regular expressions are commonly used escape sequences:

A sequence of characters meaning
\d Represents a number [0-9]
\D Representatives of non-digital [^ 0-9]
\w Represents any letter, number, underscore [0-9a-zA-Z_]
\W Represents any non-alphanumeric characters, an underscore [^ 0-9a-zA-Z_]
\s It represents a single blank characters, such as spaces or tabs
\S It represents a single non-whitespace characters
\b Word boundary, is mainly used to find regular English words, usually want to find something in one word you need to use \ b. * \ B to contain
\B Non-word boundary

Regular expressions are commonly used escape sequences:

character meaning
\n Wrap
\r Enter
\b Backspace
\t Horizontal tab, Tab key
\\ Backslash character
\[ Left parenthesis
\] Right bracket
\’ apostrophe
\. point
/[1-31]/ // 表示 1,2,3
/[0-9]/ // 表示 0,1,2,3,4,5,6,7,8,9
/[a-z]/ // 表示 a,b,c,d,e,...z
/[A-Z]/ // 表示 A,B,C,D.....Z
/a[b.c]b/ //[]中的.是字符.
/a[\[\]]b/ //表示a[]b  写在[]里面[]字符必须转义

//表示中间不要f
"abcafcadcaec".match(/a[^f]c/g) //["abc","adc","aec"]
//^如果在[]不是第一位,就表示字符^
"abcafcadcaec".match(/a[f^a]c/g))// ["afc"]

//{0}意味着匹配一个空字符
"aaaaaa".match(/a{0}/g) //["","","","","","",""]

//贪婪匹配  先匹配最大的
"aaaaaaaa".match(/a{2,5}/g)//["aaaaa","aaa"]
"aaaaaabbb".match(/a{0,4}/g)//["aaaa","aa","","","",""]
"caaaaatcbbbbt".match(/c.*t/g)//["caaaaatcbbbbt"]

//非贪婪匹配
"aaaaaaaa".match(/a{2,5}?/g)//["aa","aa","aa","aa"]
"caaaaatcbbbbt".match(/c.*?t/g)// ["caaaaat","cbbbbt"]

//或
"abcd".match(/c|b/)//["b"]
"abcd".match(/[cb]/)//["b"]
"abcdef".match(/a||b/g)//["a","","","","","",""]

//数字1-31的正则
/[1-9]|[12][0-9]|3[01]/

//群组
"18617891076".match(/(\d{3})(\d{4})(\d{4})/)// ["18617891076","186","1789","1076"]
"18617891076".match(/(\d{3})(\d{4})(\d{4})/g)//["18617891076"]

Method regular expression object

  • Whether the test () is determined to satisfy a regular string matches, the matching returns true if successful, otherwise returns false
  • exec () matches the regular search results string satisfied, the return value is found in the form of an array, only one element of the array, including several properties, namely a group index, the string itself. If no match is found, null is returned.
var reg=/a/g;
console.log(reg.test("abc"));//true
console.log(reg.exec("abaca"));//Array["a"]

exec () print out the results were as follows:
exec

The method of string matching the regular common

Order matching from left to right, press the landmark matches, match has been, and will not match again. If the current index of the character does not meet the first condition, the future will continue to match the second condition.

  • search (), returns the first matching content index or -1
  • split (), according to the regular matching cutting
  • replace (), according to replace the contents of the regular matching
  • match (), returns a successful match an array, or null

match()

  • Takes one argument, a regular string to match, if the match is successful, it returns an array of matching success, if the match is not successful, it returns null
  • 如果不加全局,可以达到exec的目的
  • 如果加有全局匹配,就会只返回找到的所有元素数组
  • 如果加有群组,但是不加全局,则除返回找到的元素外,还返回群组的元素
var str="abcadef";
console.log(str.match(/a/));//[a]
console.log(str.match(/a/g));//[a,a]
var str1="<div>内容内容</div>";
console.log(str1.match(/<(\/?.+?)>/g));//["<div>","</div>"]
console.log(str1.match(/<(\/?.+?)>/));//["<div>","div"]

replace()

按照正则表达式匹配内容进行替换,可以替换成相同的也可以替换成不同的。接受两个参数,第一个是匹配项,第二个可以是字符串或是一个函数

var str="abcdeafgh";
//将字符串中所有的a替换成z
console.log(str.replace(/a/g,"z"));//zbcdezfgh

 //str.replace(正则表达式,回调函数(item,index){
   //    return 返回要替换的内容
// })

案例:

1、将第一个a替换成x,后面的a替换成y
2、查找所有匹配正则元素的下标
3、把任何满足正则内容的进行替换
4、把对应字符替换为相对应的内容

//将第一个a替换成x,后面的a替换成y
var str="abcdeafgh";
str=str.replace(/a/g,function(item,index){
   return index===0 ? "x" : "y";
})
console.log(str);//xbcdeyfgh

//查找所有匹配正则元素的下标
var str1="abcdeafgh";
var arr=[];
str1.replace(/a/g,function(item,index){
    arr.push(index);
})
console.log(arr);//[0,5]

//把任何满足正则内容的进行替换
var str2="abcdeafgh";
console.log(str2.replace(/[bdfh]/g,"0"))//;a0c0ea0g0

//把a替换为1,b替换为2,c替换为3
var str3="abcabcadf";
str3=str3.replace(/[abc]/g,function(item){
    switch(item){
        case "a":return "1";
        case "b":return "2";
        case "c":return "3";
    }
});
console.log(str);//1231231df

search()

按照正则表达式查找字符串中的内容,返回优先查找到第一个元素下标,没有匹配项返回-1。

注意:

就算写了全局匹配,search() 也只返回找到的第一个元素的下标。

var str="abcdeafgh";
console.log(str.search(/a/g));//0
//虽然写了全局匹配,但是search只返回找到的第一个元素的下标。

split()

按照正则表达式匹配内容切割字符串,返回切割后的数组。
可以按照固定的字符进行切割,也可以按照多个字符进行切割。

var str="abcdeafgh";
//以字符"b"对字符串进行切割
console.log(str.split("b"));//["a","cdeafgh"]
//以字符"c"或者"f"对字符串进行切割
console.log(str.split(/[cf]/));//["ab","dea","gh"]

断言

断言只是条件,本身并不会匹配,能帮助你找到符合条件的字符串。

  • ?= 后置条件 向后断言,例:(?=a) 仅当表达式 a 在 此位置的右侧(后面)匹配时才继续匹配。
  • ?! 向后断言,不等于,例:(?!a) 仅当表达式 a 不在 此位置的右侧(后面)匹配时才继续匹配
  • ?<= 前置条件 向前断言,例:(?<=a) 仅当表达式 a 在 此位置的左侧(前面)匹配时才继续匹配。
  • ?<! 前置条件不等于,例:(?<!a) 仅当表达式 a 在 此位置的左侧(前面)匹配时才继续匹配。
//找到后面是d的a
"abcdadef".match(/a(?=d)/g)
//将后面是字母或者数字的a替换成1
"a0bcd adef a&cd".replace(/a(?=[a-z])|a(?=[0-9])/g,"1")

//将后面不是字母的a替换成1
"a0bc adef a&bc".replace(/a(?![a-z])/g,"1")

//将前面是数字的b替换成1
"a0bc adef a&bc".replace(/(?<=[0-9])b/g,"1")

//将前面不是数字的b替换成1
"a0bc adef a&bc".replace(/(?<![0-9])b/g,"1")

//必须包含字母数字的正则
"abacd234".match(/^(?=.*[a-z])(?=.*[0-9])\w+$/)

中文匹配:
/[\u4e00-\u9fd5]+/g)

"你好".match(/[\u4e00-\u9fd5]+/g)

案例:密码等级

低级:纯数字或者纯字母(大小写)密码(6-18)

中级:数字和字母(6-18)

高级:数字字母下划线,符号,空格,!@#¥%^&等(6-18)

/^(\d{8,16}|[a-z]{8,16}|[A-Z]{8,16})$/ //初级
/^([0-9a-zA-Z]{8,16})$/  //中级
/^([\w!@#\$%\^&\*]{8,16})$/  // 高级
Published 46 original articles · won praise 26 · views 10000 +

Guess you like

Origin blog.csdn.net/Charissa2017/article/details/103892886