Regular expression,Also known as regular notation, regular notation.(English:regular expression, often abbreviated as regex, regexp or re in code), a concept of computer science.Regular expressions use a single string to describe and match a series of rules that match a certain syntax.In many text editors,Regular expressions are often used to retrieve and replace text that matches a pattern.

First, regular expressions in javascript

In javascript, regular expressions can be constructed using regexp objects.We need to create a new instance of regexp () object, which can be passed two parameters:the first parameter is the matching pattern,The second parameter is an option,Three parameters can be passed in.i means case-insensitive,g means global matching,I.e. match all qualified strings,m means to perform multiple matches.Examples are as follows:

var reg=new regexp ("hello", "i");//Matches the hello string in the string and is not case sensitive.

Second, use exec for pattern matching

There is a method in regexp that performs pattern matching and returns the result:exec (). This method is very important.Basically, the necessary function for pattern matching using js.However, the return value of this function is not clear to many people.Therefore, in actual use, errors often occur.Here is a systematic introduction to the use of exec ().

The basic format of exec () is:regexpobject.exec (string), where regexpobject is a set regular matching object.string is the string to be matched.If it matches successfully,Returns an array;If there is no string part that successfully matches,It returns null.

The point here is this array.What exactly does the array return?Take a look at the following experiment.

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

This code performs a url match, which can be used to get the parameter part after user =,So if you use a url and use this mode for exec operation, what will the result return?For example we have the following


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

This is the rule returned by exec matching:the first element is the entire matched string,Starting from the second parameter, the string matched by each group defined by () in the pattern is returned.

This ([^&#] *) returns a string that does not start with&or #,That is the corresponding parameter later.

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

  • Previous Jsp + mysql database operation common method instance summary
  • Next Android (Android) chat robot to achieve code sharing