Regular expressions that you can understand (expressed in JavaScript)

Time:2021-2-26

I am a front-end minion, and I often use regular expressions in my work, so I took time to learn the basics of regular expressions. Today, I will share what I have learned with you. I will first show you some small examples to lead you to gradually understand regular expressions. Then, on the basis of these small examples, I will realize a regular expression that can match email address(All the cases listed in this article can be executed in the browser console)。

Go straight to the theme

1. The simplest regularization: matching specific strings
let reg = new RegExp("a")
reg.test("a")
//The result is true
reg.test("b")
//The result is false

This example is simple and direct. We use the regexp constructor to construct a regular expression object. The goal of this regular expression is to match the “a” in the string, return true if it contains, and return false if it does not.

2. Matching patterns in regular expressions

When you declare a regular expression object, you can pass a second parameter to the regular table expression: matching pattern. There are three types of matching patterns

Modifier describe
i Case insensitive matching
g Global matching
m Multiple line matching.

Here, we create a case insensitive regular expression:

//Note that the parameters of the matching pattern are also of type string
let reg = new RegExp("a","i")
reg.test("A")
//The result is true
reg.test("b")
//The result is false

Of course, regular expressions can also be created literally in JavaScript. The regular expressions created in this way are the same as the objects constructed by regexp, and the type is also object.

//Constructor mode
let reg = new RegExp("a","i")
//Literal measurement method
let reg = /a/i
3. Detect whether there is “a” or “B” in a string (case insensitive)
let reg = /a|b/i
reg.test("a")
//true
reg.test("b")
//true
reg.test("riku")
//false

When a regular expression is defined, if some characters are put into [] then the characters in [] are or, that is, it is true as long as any character is included.

4. Match any letter
let reg = /[A-z]/
reg.test("douban")
//true
reg.test("taoBao")
//true
reg.test("123")
//false

This regularization is used to match all the characters between upper case a and lower case Z. because the ASCII code of upper case letters is smaller than that of lower case letters, A-Z represents all the letters, and then put it in [] to match any case letter. Therefore, we no longer need the modifier named I to indicate that it is case insensitive.

5. Match any string of ABC, BBC and CBC
let reg = /[abc]bc/
reg.test("abc")
//true
reg.test("bbc")
//true
reg.test("cbc")
//true
reg.test("1bc")
//false
6. Match strings other than ABC
let reg = /[^abc]/
reg.test("ab")
//false
reg.test("abx")
//True because it contains the character x other than ABC
let reg = /[^0-9]/
//The regular can match any non numeric characters, more commonly used!

Adding a ^ sign before the square brackets means to match any character that is not between the square brackets.

String methods related to regularization

There are four regular methods related to strings, as listed in the following table:

Method name Specific role
search Retrieves the value that matches the regular expression
match Find a match for one or more regular expressions
replace Replace substrings that match regular expressions
split Splits a string into an array of strings

Let’s start withsplitSpeaking of:

1. Split the string according to any number
let str = "a1b2c3d4e5f6g"
let arr = str.split(/[0-9]/)
console.log(arr)
//The results were ["a", "B", "C", "d", "e", "F", "g"]

The string split method can split the string according to the specified rules,Even if no global matching is performed, split still splits the entire string

The search method of string can search whether the string contains the specified content, similar to str.indexOf () method. If it is found, the first matching index will be returned. Otherwise, – 1 will be returned. For search,Even if global matching is specified, only the first matching result is returned, that is, search cannot match globally

2. Search for user1, user2, and user3 in a string
let str = "userlist :user1 ,user2,user3"
console.log(str.search(/user[123]/))
//The result is 10, which is the index value of the first matched user1

String matching method can extract a string array from a string according to the matching result of regular expression.
By default, the match method will only match the first result and stop searching after finding it
If we want the match method to perform global matching, we only need to add the / g modifier mentioned before, or we can add the / I modifier to perform case insensitive matching.

3. Extract all the numbers in a string
let str="1a2b3c4d5e6f"
let arr = str.match(/[0-9]/g)
//The print result of arr is ["1", "2", "3", "4", "5", "6"]

str.replace () can replace the matched content in the string with the new content. Replace has two parameters:
1. Replaced content(can be regular expression)
2. The new content can be a string or a callback function. The callback function can operate on the content of each item matched.

4. Change the initials of small words in the string to uppercase
let str = "abc bbc cbc"
let reg = /\b\w+\b/g
let result = str.replace(reg, (word) => {
  return word.substring(0, 1).toLocaleUpperCase() + word.substring(1)
})
console.log(result);

In regular expressions, you can set the number of times a character appears through a quantifier, but the quantifier only takes effect on the character before it. If we want the quantifier to take effect on the previous characters, we can wrap it in brackets, for example: (AB) {3,5} means that ab appears 3-5 times, if 5 is omitted, it means that it appears 3 times or more.

The common quantifiers are as follows:

classifier Specific role
{n} Retrieves the value that matches the regular expression
{m,n} Find a match for one or more regular expressions
{m,} Replace substrings that match regular expressions
+ At least once, equivalent to {1,}
* 0 or 1 or more times, equivalent to {0,}
? 0 times or once, equivalent to {0,1}
5. Judge whether a string is a legal mobile phone number
let phoneReg = /^1[3-9][0-9]{9}$/
phoengReg.test('13123456789')
//The result is true. Our verification rule here starts with 1, and the second digit is any number between 3 and 9,  
//The remaining nine digits are arbitrary, so the total number of digits is 11  
//The start ^ sign indicates the start and the last $sign indicates the end of the string.
6. Remove all spaces at the beginning and end of a string
let str  = "   hello   world    "
let strReg = /^\s*|\s*$/g
str = str.replace(strReg,"")
//The execution result is "Hello world", where you need to specify global matching, otherwise only the preceding space will be matched.

Here, I also want to introduce the concept of metacharacter, which is used in our previous case. It represents any space. The metacharacters commonly used in regular expressions are shown in the following table:

Metacharacter Specific meaning
\w Any letter, number, underline [a-z0-9]
\W Except letters, numbers and underscores
\d Any number [0-9]
\D Except for the number [^ 0-9]
\s Space
\S Except for the space
\b Word boundary
\B Except for word boundaries

Regular matching mailbox

Normally, an email address consists of the following parts
We take test.zhou @ test.com.cn For example, the mailbox is divided into the following parts:
① The matching rules of test ﹣ ②. Zhou ﹣ ③ @ ④ test ﹣ ⑤. Com ﹣ ⑥. CN are as follows:

Arbitrary length string:
\w{3,}
“.” or “_ “+ string of any length (optional):”
((\.|\_)\w+)*
“@” symbol
@
Any length alphanumeric:
[A-z0-9]+
“. + string of length 2-6:
\.[A-z]{2-6}
“. + string of length 2-5 (optional)
\.[A-z]{2-5}

Finally, we integrate the six parts we just analyzed to get the regular expression we want to check the mailbox

let emailReg = /\w{3,}((\.|\_)\w+)*@[A-z0-9]+\.[A-z]{2,6}(\.[A-z]{2,5})*/
emailReg.test("[email protected]") //true
emailReg.test("[email protected]") //true

summary

This paper starts with the simplest string matching, introduces how to use regular expressions to match target objects in JavaScript, then introduces the matching pattern of regular expressions, and then introduces four methods of combining string and regular expressionssearchmatchreplacesplitFinally, the regular matching expression of a mailbox is realized by using the basic knowledge of regular expression.
This paper aims to help students develop regular expressions, help you use regular expressions in your work, and pave the way for further study of regular expressions.

Recommended Today

Third party calls wechat payment interface

Step one: preparation 1. Wechat payment interface can only be called if the developer qualification has been authenticated on wechat open platform, so the first thing is to authenticate. It’s very simple, but wechat will charge 300 yuan for audit 2. Set payment directory Login wechat payment merchant platform( pay.weixin.qq . com) — > Product […]