Construct regular expression validation using exec of method in JS

  • 2021-07-07 06:09:46
  • OfStack

Regular expression, also known as normal notation and conventional notation. (English: Regular Expression, which is often abbreviated as regex, regexp or RE in code), a concept of computer science. Regular expressions are described by a single string, and matching 1 series conforms to a syntactic rule. In many text editors, regular expressions are often used to retrieve and replace text that conforms to a certain pattern.

1. Regular expressions in Javascript

In Javascript, you can use RegExp objects to construct regular expressions. We need to create a new instantiated RegExp () object, which can pass in two parameters: the first parameter is a matching pattern, and the second parameter is an optional one, which can pass in three parameters. i means case-insensitive, g means global matching, that is, matching all qualified strings, and m means performing multiple matches. Examples are as follows:


var reg = new RegExp("Hello", "i"); // Represents a match in the string Hello String and is not case sensitive.

2. Pattern matching using exec

There is one method in RegExp that performs pattern matching and returns the result: exec (). This method is very important, and it is basically a necessary function for pattern matching using js. However, the return value of this function is not clear to many people, so errors often occur in actual use. Here, we systematically introduce the use of exec ().

The basic format of exec () is: RegExpObject. exec (string), where RegExpObject is the set regular match object and string is the string to be matched. If the match is successful, 1 array is returned; If there is no successful matching string part, null is returned.

The focus here is on this array. What exactly does the array return? You can look at the following experiment.


var re = new RegExp("[?#&]" + user + "=([^&#]*)", "i")

This code matches an url, which can be used to get the parameter part after user =, so if you use an url and operate exec with this pattern, what will be returned? For example, we have the following

www.qq.com?user=Tom & psw=123456

The array result returned by exec is: [? user = Tom, Tom]. You can see that the first element of the return array is the string to which the entire matching pattern matches, and the second character to which the matching pattern matches happens to be the parameter value.

This is the exec match return rule: The first element is the entire match string, and starting with the second parameter, the string matched by every group defined by () in the pattern is returned.

Here ([^ & #] *) Returns a message that does not use the & Or the string beginning with #, that is, the corresponding parameter after it.

If we change the defined schema to [? # & ]" + (user) + "=([^ & #] *), then the array returned after exec () is [? user = Tom, user, Tom].


Related articles: