Regular expression

  • Be able to tell what regular expressions do
  • Write simple regular expressions
  • The ability to validate forms using regular expressions
  • The ability to replace content with regular expressions
  1. Overview of regular expressions
  2. Use of regular expressions in JavaScript
  3. Special characters in regular expressions
  4. Substitutions in regular expressions

1. Overview of regular expressions

1.1 What is a regular expression

Regular expressions are patterns used to match combinations of characters in strings. In JavaScript, regular expressions are also objects.

Regular expressions are used to retrieve and replace text that matches a pattern.

  • Chinese can be entered in the input box (match)
  • Sensitive word substitution (substitution)
  • Get our specific part of the string (extract)

1.2 Features of regular expressions

  • It’s flexible, logical, and functional
  • Can be used quickly, extremely simple way to achieve complex character control
  • For people who are new to it, it’s kind of obscure.
  • In practice, regular expressions are usually copied and pasted directly, but it requires that we know how to use regular expressions and modify them accordingly. For example, user name: /^[a-z0-9_-]{3,16}$/

2. Use of regular expressions in JavaScript

2.1 Creating regular expressions

Regular expressions can be created in JavaScript in two ways:

  1. The regular expression is created by calling the RegExp object
  2. Regular expressions are created using literals
//1. Create regular expressions by calling the RegExp object
var regexp = new RegExp(/ 123 /)
console.log(regexp) / / / / 123

//2. Create regular expressions using literals
var reg = / 123 /
console.log(reg) / / / / 123
Copy the code

2.2RegExp Object methods

(1) Test regular expression test()

The test() regular expression method, used to test if a string conforms to this rule, returns true or false and takes the string to be tested as an argument.

var reg = / 123 /
console.log(reg) / / / / 123

console.log(reg.test("12345")) //true
console.log(reg.test("abc")) //false
Copy the code

(2) exec()

Regexpobject. exec(string) returns an array containing matching results. If no match is found, the return value is null.

var str = "Visit W3School, W3School is a place to study web technology."; 
var patt = new RegExp("W3School"."g");
var result;

while((result = patt.exec(str)) ! =null)  {
  console.log(result); // Returns the result of the match in an array format
  console.log(patt.lastIndex); // Returns the last position where the matching result appears
}
Copy the code

Output result:

3 Special characters in the regular expression

A regular expression can consist of simple characters, such as/ABC /, or a combination of simple and special characters, such as /ab*c/. Special characters are also called metacharacters. They are special characters with special meanings in regular expressions, such as ^, $, and +

3.1 There are many special characters, you can refer to:

  • MDN:
  • Jquery Manual: Regular expressions section
  • Regular test tools:

3.2 Boundary: ^ $

A boundary character (position character) in a regular expression is used to indicate the position of a character. It consists of two characters.

Boundary operator instructions
^ The text that matches the beginning of the line (with whom to start)
$ The text that matches the end of the line (with whom it ends)

If ^ and $are together, it must be an exact match.

         // Boundary ^ $
        // Regular expressions do not require quotation marks, either numeric or string

        var rg= /abc/  // The string contains ABC
        console.log(rg.test("aabcd")) //true

        var rg2=/^abc/ // The description must start with ABC
        console.log(rg2.test("abc")) //true
        console.log(rg2.test("aabc")) //false

        var rg3=/^abc$/ // The string must be ABC, because it starts with ABC and ends with ABC, and is 3 characters in length
        console.log(rg3.test("abc")) //true
        console.log(rg3.test("abcabc")) //false
Copy the code

3.3 Character Class [] :

[] indicates that there are a series of characters to choose from, and you only need to match one of them. This is called a character class. All optional characters are in square brackets.

[^] — invert the values inside brackets, no matter how many values are inside.

 /^[^abc]$/.test("a") //false
 /^[^abc]$/.test("Q") //true
 /^[^abc]$/.test("b") //false
Copy the code

Note: the first ^ represents the boundary character, the second ^ represents the inverse.

identifier instructions
/[abc]/ The value can contain any of a, B, or c
/^[abc]$/ Indicates that only one of three strings can be selected
/^[a-z]$/ Indicates that the string can be any one of 26 characters
/^[a-z0-9A-Z-_]$/ Indicates that the string must be one of the following: A-Z A- z 0-9 – _
var rg = /[abc]/ // indicates that as long as the string contains a or b or c things are correct
        console.log(rg.test("accc")) //true
        console.log(rg.test("red")) //false

        var rg1 = /^[abc]$/ // Indicates that only one of three strings can be selected
        console.log(rg1.test("a")) //true
        console.log(rg1.test("c")) //true
        console.log(rg1.test("abc")) //false

        var rg2 = /^[a-z]$/ // Indicates that the string is any one of 26 characters
        console.log(rg2.test("z")) //true
        console.log(rg2.test("az")) //false

        var rg3 = /^[a-z0-9A-Z-_]$/ // Indicates that the string is one of the following: a-z a-z 0-9 - _
        console.log(rg3.test("Z")) //true
        console.log(rg3.test("A_")) //false

        var rg4 = /^[^a-z0-9A-Z-_]$/ // Indicates that the string cannot be one of the following characters: A-z A-z 0-9 - _
        console.log(rg4.test("A")) //false
        console.log(rg4.test("?")) //true
Copy the code

3.4 Quantity characters * +? {n}

The measure character is used to set the number of times certain patterns occur

quantifiers instructions
* Repeat 0 or more times
+ Repeat 1 or more times
? Repeat 0 times or 1
{n} Repeated n times
{n,} Repeat n times or more
{n,m} Repeat n to m times
var reg=/^a*$/   // * Repeat 0 or more times
        console.log(reg.test("")) //true
        console.log(reg.test("a")) //true
        console.log(reg.test("aaa")) //true


        var reg1=/^a+$/   // + repeat 1 or more times
        console.log(reg1.test("")) //false
        console.log(reg1.test("a")) //true
        console.log(reg1.test("aaa")) //true

        var reg2=/^a? $/   / /? Repeat 0 times or 1
        console.log(reg2.test("")) //true
        console.log(reg2.test("a")) //true
        console.log(reg2.test("aaa")) //false

        var reg3=/^a{3}$/   // {n} repeat n times
        console.log(reg3.test("")) //false
        console.log(reg3.test("a")) //false
        console.log(reg3.test("aaa")) //true

        var reg4=/^a{3,}$/   // {n,} repeat n times or more
        console.log(reg4.test("")) //false
        console.log(reg4.test("a")) //false
        console.log(reg4.test("aaa")) //true
        console.log(reg4.test("aaaa")) //true

        var reg5=/ ^ {3, 4} $/ a   // {n,m} repeat n to m times
        console.log(reg5.test("")) //false
        console.log(reg5.test("a")) //false
        console.log(reg5.test("aaa")) //true
        console.log(reg5.test("aaaa")) //true
        console.log(reg5.test("aaaaa")) //false
Copy the code
var rg3 = / ^ [a - z0-9 a - Z - _] {3, 4} $/
console.log(rg3.test("aaz")) //true
console.log(rg3.test("abcs")) //true
console.log(rg3.test("abdsf")) //false
Copy the code

Example: Is the user name input format correct

<head>
    <style>
        .right{background-color: green; }.left{background-color: red; }</style>
</head>
<body>
    <input type="text" name="Username" id=""><span>Please enter a user name</span>
    <script>
        var reg = / ^ [a - zA - Z0-9 - _] 6 16th} {$/
        var uname = document.querySelector("input")
        var uspan = document.querySelector("span")
        
        uname.onblur=function(){
            if(reg.test(this.value)){
                uspan.setAttribute("class"."right")
                uspan.innerHTML="User name format is correct"
            }else{
                uspan.setAttribute("class"."left")
                uspan.innerHTML="User name format error"}}</script>
</body>
Copy the code

3.5 Parenthesis summary :{} [] ()

  1. Braced quantifier {} : inside indicates the number of repetitions
  2. Bracket character set [] : Matches any character in square brackets
  3. The parentheses indicate the priority ()
var reg=/^abc{3}$/
  console.log(reg.test("abc")) //false
  console.log(reg.test("abcabcabc")) //false
  console.log(reg.test("abccc")) //true

  var reg2=/^(abc){3}$/
  console.log(reg2.test("abc")) //false
  console.log(reg2.test("abcabcabc")) //true
  console.log(reg2.test("abccc")) //false

 	var reg5 = /^[abc]{3}$/
  console.log(reg5.test("abc")) //true ABC three times any of the three is correct
	console.log(reg5.test("abccc")) //false
	console.log(reg5.test("aaa")) //true
Copy the code

Online testing tool

3.6 Predefined Classes

Predefined classes are shorthand for some common matching patterns

Booking class instructions
\d Matching any number between 0 and 9 is equivalent to [0-9]
\D Matching characters other than 0-9 is equivalent to [^0-9]
\w Matching any letter, digit, or underscore is equivalent to [A-zz-z0-9_].
\W Matching characters except letters, digits, and underscores are equivalent to [^ A-zz-z0-9_].
\s Matching Spaces (including newlines, tabs, Spaces, etc.) are equivalent to [\t\n\v\f]
\S Characters that match non-spaces (including newlines, tabs, Spaces, etc.) are equivalent to [^\t\n\v\f]
<script>
  var reg=/\d/
	console.log(reg.test("123")) //true
	console.log(reg.test("abc")) //false
</script>
Copy the code