A regular expression is a pattern used to match the combination of characters in a string, that is, to search, replace, and extract information in a string. The following is my arrangement and summary of regular expressions in JS. If you find any problems with this article, please point them out in the comments.
1. Rehash common syntax
1.1 Matching Mode
Example: // Get all matches, Const testString = 'test test test abdskxc ioewhsnc' const reg = /test/gi console.log(testString.match(reg)) // [ 'test', 'Test', 'tEsT' ]Copy the code
1.2 Basic and special metacharacters
Example: / / using the operator | const reg = / yes | no | strategized / / / match any character. As a placeholder for any character const regexp = /. At /gi const testString = 'cat Bat mat DOG egg FAT cupcake sing' console.log(testString.match(regexp)) // [ 'cat', 'Bat', 'mat', [] const testReg = /[CMF]at/g console.log(testString.match(testReg)) // ['cat', Const regTest = /[a-d]at/ const str1 = 'cat', str2 = 'fat', str3 = 'bat' console.log(regTest.test(str1), regTest.test(str2), Regtest. test(str3)) // true false true // Match specific numbers and letters const reg1 = /[a-z0-9]/gi const testString1 = 'sagiga46323' Console. log(reg1.test(testString1)) // true // Matches a single unknown character const reg2 = /[^aeiou]/gi // Matches all letters and numbers const longReg = /[A-Za-z0-9_]+/ const shortReg = /\w+/ const num = '46313' const str4 = 'dsiohdkcsds' console.log(longReg.test(num), Test (num), longrego. test(str4), shortreg.test (str4)) // true true true true Const reg3 = /\w/gi const str5 = '! _ $!!!!! 'const str6 = 'sj456AyTB' console.log(reg3.test(str5)) // true console.log(reg3.test(str6)) // true // Matches all numeric const DigitReg = /\d/g const strDigit = 'The shirt is $35.12' console.log(strDigit. Match (digitReg)) // ['3', '5', '1', // match all nonDigitReg const nonStr = /\D/g const nonStr = '463 DSHKFSD 'console.log(nonstr.match (nonDigitReg)) // [', 'd', 's', 'h', 'k', 'f', 's', Const sentence = 'I like mike' console.log(sentence.match(senReg)) // [' ', '] / / match the space const nonsenReg = / \ S/g console. The log (sentence. Match (nonsenReg)) / / / 'I', 'l', 'I' and 'k', 'e', 'm', 'I' 'k', 'e']Copy the code
1.3 quantifiers
Quantifiers indicate how many target objects are matched. The exact matching length is {}.
Example: // Match one or more characters in a line const oneOrMoreReg = /a+/gi const oneOrMoreStr = 'sahiohankdahka' console.log(oneOrMoreStr.match(oneOrMoreReg)) // [ 'a', 'a', 'a', 'A'] // Match zero or more consecutive occurrences of const zeroOrMoreReg = /hi*/gi const zeroOrMoreStr = 'ahiadahHCAST' const zeroOrMoreStr2 = 'adakskmd' console.log(zeroOrMoreStr.match(zeroOrMoreReg), zeroOrMoreStr2.match(zeroOrMoreReg)) // [ 'hi', 'h', 'hi'] null // lazy match // In the case of no one, the regular expression is greedy, i.e. matches the longest part of the string that meets the given requirement // use? Const greedyReg = /c[a-z]*t/gi const lazyReg = /c[a-z]*? t/gi const testStr7 = 'catshidtasji' console.log(testStr7.match(greedyReg), Teststr7. match(lazyReg) // ['catshidt'] ['cat'] // Match number of characters const regular = 'hihi' const superHi = 'hadiojknejodmc' Const regx = /hi{1,4}/ console.log(regx.test(regular), Regx.test (superHi)) // true false // Minimum number of characters to match const strHi = 'hiiiii' const hiReg = /hi{3,}/ console.log(hiReg.test(regular), hiReg.test(superHi), Test (strHi)) // false false true // Match the exact number of characters const exactReg = /hi{4}/ console.log(exactreg.test (strHi), Exactreg.test (regular)) // true false // Match 0 or 1 times const colSpell = 'Colour' const colSpelling = 'color' const colReg = /colou? r/i console.log(colReg.test(colSpell), colReg.test(colSpelling)) // true trueCopy the code
1.4 the boundary
Example: Const str8 = 'hello world' const str9 = 'world is beautiful, hello' const startReg = /^hello/ console.log(startReg.test(str8), Test (str9)) // true false // Match end string const endReg = /hello$/ console.log(endreg.test (str8), endReg.test(str9)) // false trueCopy the code
1.5 grouping
Example: console.log(`ashinmdnkbdkchbjduigh`.replace(/h(inm|bj)d/g, '-')) // as-nkbdkc-uigh console.log('2021-01-08'.replace(/(\d{4})\-(\d{2})\-(\d{2})/g, '$2/$3/$1')) // 01/08/2021 let reg = /\d{4}(\-|\/|.) 1 \ \ d {1, 2} \ d {1, 2} / console log (reg. Test (' 2021-01-08 '), Reg.test ('2021-01.08')) // true false // forward forward with xx console.log('4a5d6sa4da5c1x'. Replace (/\w(? = \ d)/g, '-')) / / in the 4-5-6 s - 4-5-1 x/d/a negative perspective Cannot have xx behind the console. The log (' 4 a5d6sa4da5c1x. Replace (/ \ w (? ! \ d)/g, '-')) / / - a - d - a - a - c - / / is long front to have xx const regexp1 = / (? <=\$)\d+/u const str = 'shirt $463' console.log(regexp1.exec(str)) // [ '463', index: 7, input: 'shirt $463', groups: Undefined constant xx const regexp2 = /(? <! \$)\d+/u console.log(regexp2.exec(str)) // [ '63', index: 8, input: 'shirt $463', groups: undefined ]Copy the code
1.6 Case Conversion
1.7 Priority Order
The following lists the order of priorities from highest to lowest:
(1) Escape: \
(2) parentheses and square brackets :(), (? :), (? =), []
(3) qualifiers: *, +,? , {n}, {n,}, {n,m}
(4) Position and order: ^, $, \anymetacharacter
(5) “or” operation: |
2. Js RegExp object
In JS, regular expressions are represented by RegExp objects, which can be written in two ways: literal writing and constructor writing.
2.1 Constructors
let reg = new RegExp('<%[^%>]+%>', 'g');
Copy the code
2.2 literal
let reg = /<%[^%>]+%>/g
Copy the code
Regular expression functions in 2.3 JS
2.3.1 String. The prototype. The search method
Used to locate the first occurrence of a string, returning the position where the first character was found, or -1 if none exists. This method does not perform global matching. It ignores the g modifier and always retrieves from the beginning of the string.
console.log('abchello'.search(/hello/)) // 3
console.log('abchell'.search(/hello/)) // -1
Copy the code
2.3.2 String. The prototype. The replace method
Replaces a substring in a String, which can take String, Number, or the callback function.
console.log('abchello'.replace(/hello/, 'hi')) / / abchi let STR = 'sgudcbsjbckankdanknfnsndndcksnck' const arr = STR. The split / \ s * / / / the string into an array of const str2 = Arr.sort ().join('') Str2. replace(/(\w)\1*/g, function($0, $1) {if (index < $0.length) {index = $0.length value = $1 // value corresponding character}}) Console. log(' most characters: ${value}, repeat times: ${index} ') // Most characters: n, repeat times: 7Copy the code
2.3.3 String. The prototype. The test method
Used to test if there are substrings in a string. When the g modifier is used with this method, the re remembers the lastIndex property and starts checking from lastIndex the next time it executes.
console.log(/hello/.test('abchello')) // true
Copy the code
2.3.4 String. The prototype. The split method
Used to split a string into multiple substrings.
console.log('qwehelloasdfhellozxvnmxhellohkjp'.split(/hello/)) // [ 'qwe', 'asdf', 'zxvnmx', 'hkjp' ]
Copy the code
2.3.5 String. The prototype. The match method
Captures substrings of a string into an array. By default, only one result is captured into the array.
console.log('qwehelloasdfhellozxvnmxhellohkjp'.match(/hello/)) // [ 'hello' ]
console.log('qwehelloasdfhellozxvnmxhellohkjp'.match(/hello/g)) // [ 'hello', 'hello', 'hello' ]
Copy the code
2.3.6 String. The prototype. The exec method
This method is similar to the string match method in that it captures the strings that meet the criteria from the string into the array, but only one substring can be captured into the array at a time.
console.log(/hello/g.exec('qwehelloasdfhellozxvnmxhellohkjp')) // [ 'hello' ]
Copy the code
There is a lastIndex attribute in the RegExp object that indicates where to start the next capture, and each time the exec method executes, lastIndex is pushed back until no matching character is found and null is returned, and the capture continues from the beginning.
Let reg = / hello/g the console log (reg. LastIndex) / / used to facilitate capturing the substring in the string 0 reg. The exec () 'qwehelloasdfhellozxvnmxhellohkjp' console.log(reg.lastIndex) // 8 reg.exec('qwehelloasdfhellozxvnmxhellohkjp') console.log(reg.lastIndex) // 17 reg.exec('qwehelloasdfhellozxvnmxhellohkjp') console.log(reg.lastIndex) // 28 reg.exec('qwehelloasdfhellozxvnmxhellohkjp') console.log(reg.lastIndex) // 0Copy the code
3. Common examples
3.1 Example 1: Check whether it is a valid mobile phone number
Let STR = '13807562276' let reg = new RegExp('1[3578]\\d{9}') console.log(reg.test(STR)) // true STR = '16794232379' console.log(reg.test(str)) // falseCopy the code
3.2 Extract all 7 valid digits in the text
Let text = 'text content, 1234567, cost 4564613 yuan, 'let res = new RegExp('\\d{7}', 'g') while ((result = res.exec(text))! = null) {console.log(result, res.lastindex)} // result // [/ '1234567', // index: 5, // input: 'text content, 1234567, cost 4564613 yuan to complete 9745638 plans ', // groups: undefined //] 12 // [// '4564613', // groups: undefined //] 22 // [// '9745638', // index: 29, // index: 29, // input: 'Text content, 1234567, cost 4564613 yuan to complete 9745638 plans ', // groups: undefined //] 36Copy the code
3.3 User names are regular
/ / the user name, 4-16 (including letters, Numbers, underscores, minus) const reg = / ^ [a zA - Z0 - _ - 9] 16th {4} $/; console.log(reg.test('dabai')); // trueCopy the code
3.4 Password strength is regular
// A string of at least 6 to 16 characters, including at least one uppercase letter, one lowercase letter, one digit, and one special character. (=. 16th {6})? =.*\d)(? =.*[A-Z])(? =.*[a-z])(? =. * [! @ # $% ^ & *? \ (\)]) * $/;; console.log(reg.test('daBai2021*')) // trueCopy the code
3.5 Id number regularization
let reg = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
console.log(reg.test('11010519780603375X')) // true
Copy the code
3.6 Hexadecimal color is regular
let reg = /^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/
console.log(reg.test('#fcfcfc'), reg.test('#fff')) // true true
Copy the code
3.7 Integer Regularization
/ / regular positive regular negative integer regular integers let posReg = / ^ \ d + $/, negReg = / ^ - \ d + $/, intReg = / ^ -? \d+$/ console.log(posReg.test('613'), negReg.test('-7946'), intReg.test('5463')) // true true trueCopy the code
3.8 Digital Regularization
// Numbers can be integers or floating-point numbers. Let posReg = /^\d*\.? \d+$/, negReg = /^-\d*\.? \d+$/, numReg = /^-? \d*\.? \d+$/ console.log(posreg. test('56.12'), negrego. test('-78.16'), numreg. test('46123.56')) // true true trueCopy the code
3.9 Date Regularization
/ / a simple decision let reg = / ^ \ d {4} (\) \ d {1, 2} \ \ d {1, 2} $1 / console log (reg. Test (' 2021-01-08 ')) / / true / / complex decision let reg2 = / ^ (? : (? ! 0000) [0-9] {4} - (? : (? : 0 | [1-9] [0-2] 1) - (? : 0 [1-9] [0-9] | | 1 2 [0 to 8]) | (? : 0 [9] 13 - | [0-2] 1) - (? 30) : 29 | | (? : 0 [13578] 1 [02]) - 31) | | (? : [0-9] {2} (? : 0 [48] | [2468] [048] | [13579] [26]) | (? :0[48]|[2468][048]|[13579][26])00)-02-29)$/ console.log(reg2.test('2021-01-08')) // trueCopy the code
3.10 Includes Chinese regular
Let reg = /[\ u4e00-\ u9FA5]/ console.log(reg.test(' u4E00 ')) // trueCopy the code
3.11 Regular license plate number
[a-z]{1}[a-z]{1}[A-z]{1}[A-z]{2}[a-z0-9]{4}[A-z0-9 hang student police Hong Kong and Macao]{1}$/ Console. log(reg.test(' gan A56896')) // trueCopy the code
3.12 the URL regular
let reg = /^((https? |ftp|file):\/\/)? ([\ \. Da - z -] +) \. ([a-z \.] {2, 6}) (/ \ \ / \ w - *) * \ /? $/ console.log(reg.test('http://www.baidu.com')) // trueCopy the code
3.13 QQ Number is regular
Let reg = / ^ (1-9] [0-9] {4, 10} $/ console log (reg. Test (' 56213147 ')) / / trueCopy the code
3.14 Micro signal is regular
// 6-20 characters, starting with a letter, Contain letters, Numbers and minus sign, underline the let reg = / ^ [a zA - Z] ([a zA - Z0-9 - _] {5} 3) + $/ console log (reg. Test (' dabai456_sh - 2021 ')) / / trueCopy the code
3.15 Email is regular
Let reg = / ^ ([A Za - z0-9 _ \ - \]) + @ ([A - Za - z0-9 _ \ - \]) + \. ([A Za - z] {2, 4}) $/ console log (reg. Test (' 23233232 @qq.com ')) / / trueCopy the code
3.16 IPv4 Address is regular
let reg = /^(? : (? : 25 [0 to 5] | 2 [0 to 4] [0-9] | [01]? [0-9] [0-9]?) \.) {3} (? : 25 [0 to 5] | 2 [0 to 4] [0-9] | [01]? [0-9] [0-9]?) $/ console log (reg. Test (' 192.168.47.26)) / / trueCopy the code
Reference source
- Regular Expressions must Know must Know
- Developer.mozilla.org/zh-CN/docs/…
The last
If you like my article please ” give a like“”comments“”Focus on “Everyone’s support is my motivation to keep going! If there are any mistakes or inaccuracies in the above content, welcome to point out, if you have a better idea, also welcome to exchange and study together!