preface
This article summarizes the relevant knowledge points of regular expressions. If you have different opinions on the answers, please kindly add the discussion in the comments section. Of course, you are welcome to point out the questions in the comments section.
1. Concise grammar:
let expression = /pattern/flags ;
// pattern Matches the mode flags
Copy the code
2. Flags
- G (global mode) : Finds the entire contents of a string
- I (case insensitive)
- M (multi-line mode) : The search continues to the end of a line
- ^ : beginning of a string
- $: end of the string
Metacharacters
*, +,? , $^,., |,, (,), {and}, [and] / / escapedCopy the code
Predefined classes and boundaries
(All capital letters are “not”)
character | Equivalence class | meaning |
---|---|---|
. | [^ \r \n] | All characters except carriage returns and newlines |
\d | [0-9] | Numeric characters |
\s | [\t \n \x 0 B\ f \r] | Whitespace characters |
\w | [a-z A-Z _ 0-9] | Word characters (letters, numbers, underscores) |
\b | Ab, dsab | Word boundariesbound |
5. Character classes
The expression '[ABC]' classifies the character a or b or c as a class of characters with the reverse '[^ ABC]'Copy the code
6. Scope class
[A-zA-z] Uppercase letters [0-5] 0 to 5Copy the code
Seven, quantifiers
character | meaning |
---|---|
? | Zero or one occurrence (maximum one occurrence) |
+ | Appear once or more (at least once) |
* | Zero or more occurrences (any occurrence) |
{n} | A n time |
{n,m} | N to m occurrences |
{n,} | At least n times |
var reg = /\d{4}[/-]\d{2}[/-]\d{2}/g;
var text = 2018-02-23, 2018/02/24, 2018-02/25 ';
var result = text.replace(reg,'Match the correct date format');
console.log(result);// Match the correct date format, match the correct date format, 2018 to 02/25
Copy the code
8. Greed Mode
let str = 'Hello World el'
let regExp = / el/g {1, 2} // Match as many characters as possible
console.log(str.match(regExp)) //[ 'ell', 'el' ]
Copy the code
Nine, grouping
let str = 'Hello World elel'
let regExp = /el{2}/g // just repeat l
let regExp1 = /(el){2}/g // Repeat ()
console.log(str.match(regExp)) //[ 'ell' ]
console.log(str.match(regExp1)) //[ 'elel' ]
Copy the code
1, or [], |
The ‘[]’ character class (set of characters) may only match or relationships of a single character, such as a or B. You can write it like this: ‘[ab]’
let regExp = /[abc]/ // Matches a or B or C, matching a single character
let regExp = /(ll|or)/g // Match ll or OR, match multiple characters
Copy the code
2. Quote ()
- () will save the matched value of each group. The matched value can be 1 for the first match, 1 for the first match, 1 for the first match, 3 for the third match, and so on to $99.)
// Replace date '2015-12-25' with '12/25/2015'
let date = '2015-12-25'
let regExp = /(\d{4})-(\d{2})-(\d{2})/g
console.log(date.replace(regExp,'$1 / $2 / $3'))
/ / the key
\1Is a reference to the first matched stringconst str ='hello world';
const reg = /([a-zA-Z])\1/;
console.log(str.match(reg))
//[ 'll', 'l', index: 2, input: 'hello world', groups: undefined ]
// Can be used to test whether the string contains the same consecutive characters
console.log(reg.test(str)) //true
Copy the code
3. Non-capture meta? : and? =,? < =,? ! ,? <! The difference between
- ? : —- Using parentheses () has the side effect of making the matching string cached. : put it in parentheses where you want to eliminate the match, and it won’t take up $1.
var reg = / (? :Byron)(\d{4})-(\d{2})-(\d{2})/g;
var text = 'Byron2016-12-05'
var result = text.replace(reg,'$2 / $3 / $1');
console.log(result);/ / 12/05/2016
Copy the code
- ? = —– forward lookup to match the search string at any point where the regular expression pattern inside the parentheses begins to match
exp1(? =exp2) : select exp1 from exp2.'1234hzy123hzy341hzy'.replace(/hzy(? =\d+)/g.function (item){
console.log(item) // hZY hZY matches at least one number before hzy}) high order -- thousands character'1234567890'.replace(/ \ d {1, 3} (? =(\d{3})+$)/g.function (item){
console.log(item) // 1 234 567
});
Copy the code
- ? ! —– negative pre-check to match the search string at any location that does not initially match the regular expression pattern
(? <=exp2)exp1: = exp1(? ! Exp2) : find exp1 (? <! Exp2)exp1: find exp1 that does not start with exp2Copy the code
Application in JavaScript
New RegExp() dynamically generates regular expressions
let key = 'name'
const reg = new RegExp("([^ | &])"+ key + "([^ &] +) (& | $)"."g")
Copy the code
1, the regular expression RegExp object itself method
- Reg.test () can only test for inclusion and returns a bool.
- Reg.exec () can match globally and return grouped results
- reg.compile()
let str = 'Hello World'
let regExp = /o/g
console.log(regExp.test(str)) // true
console.log(regExp.exec(str)) //[ 'o', index: 4, input: 'Hello World', groups: undefined ]
console.log(regExp.exec(str)) //[ 'o', index: 7, input: 'Hello World', groups: undefined ]
console.log(regExp.exec(str)) //null
Copy the code
2, support regular expression String object method
-
Str.match (), unlike test(), returns what you matched. Return as an array
-
Str.split () splits the string by a character, returning an array
-
STR. The replace (STR). Replace (reg, replace | function), the first parameter is the regular expression, on behalf of the match, the contents of the second parameter is the replacement string or a callback function
- Note: The second argument must be a string; Be careful not to forget to add
g
- Note: The second argument must be a string; Be careful not to forget to add
-
Str.search () returns the index of the first matching string
let str = 'Hello World'
let regExp = /o/g
console.log(str.match(regExp)) //['o','o']
// Replace the vowel (aeiou) in a sequence with a double. For example, a - > aa
console.log(str.replace(/([aeiou])/g."$1 $1")) //Heelloo Woorld
console.log(str.search(regExp)) // 4 Returns the index of the first matching string
Copy the code
Reg. Exec (STR) differs from str.match(reg)
In the case of a global match, there are'g'They are differentlet str = 'waddsadds'
let temp = 'add'
let reg = new RegExp(temp,'g');
console.log(reg.exec(str),str.match(reg))
// [ 'add', index: 1, input: 'waddsadds', groups: undefined ] [ 'add', 'add' ]No global match. None'g'They are the samelet str = 'waddsads'
let temp = 'add'
let reg = new RegExp(temp);
console.log(reg.exec(str),str.match(reg))
[ 'add'.index: 1.input: 'waddsads'.groups: undefined ] [ 'add'.index: 1.input: 'waddsads'.groups: undefined ]
Copy the code
The IP address
let str = '226.1.255.25' / / 0 ~ 255.255.255.255 0 ~ 9, 10 ~ 99100 ~ 199
let regExp = /^((25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d).) {3}(25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/
console.log(str.match(regExp))
Copy the code
conclusion
Feel good writing, helpful to you, you can share with people around you, the more you share knowledge, do not be stingy
Follow-up update front-end other knowledge summary, please pay attention to me, tidy up, share with you, we learn front-end together