JavaScript Regular Expression notes

Source: Internet
Author: User

G represents global match
M stands for multi-line matching
I stands for case-insensitive matching
^ matches the starting position of the input string
$ matches the end position of the input string
* matches the preceding subexpression 0 or more times. Equivalent to {0,}
+ matches the preceding subexpression one or more times. Equivalent to {1,}
? Matches the preceding subexpression 0 or one time. Equivalent to {0,1}, when the character follows any other restriction (*, +,?, {n}, {n,}, {n,m}), the matching pattern is non-greedy. The non-greedy pattern matches the searched string as little as possible, while the default greedy pattern matches as many of the searched strings as possible. For example, for the string "oooo", ' o+? ' will match a single "O", while ' o+ ' will match all ' o '.
\d matches a numeric character. equivalent to [0-9]
\d matches a non-numeric character. equivalent to [^0-9]
\w, equivalent to "[a-za-z0-9_]"
\w matches any non-word character, equivalent to "[^a-za-z0-9]"
\s matches any whitespace character, including space tab breaks, and so on. equivalent to [\f\n\r\t\v]
\s matches any non-whitespace character. equivalent to [^\f\r\n\t\v]
\b Matches a word boundary, which is the position between a word and a space.
\b Matches a non-word boundary.

(pattern): matches pattern and obtains this match.

(?:p Attern): matches the pattern but does not get a matching result, which means that this is a non-fetch match and is not stored for later use. This is useful when using the "or" character (|) to combine parts of a pattern. For example, ' Industr (?: y|ies) is a more abbreviated expression than ' industry|industries '.

(? =pattern): Forward-checking, matching the lookup string at the beginning of any string that matches the pattern. This is a non-fetch match, which means that the match does not need to be acquired for later use. For example, ' Windows (? =95|98| nt|2000) ' Can match Windows 2000 ', but does not match Windows 3.1 in Windows. Pre-checking does not consume characters, that is, after a match occurs, the next matching search starts immediately after the last match, rather than starting with the character that contains the pre-check.

(?! Pattern): Negative pre-check, in any mismatch negative lookahead matches the search string at any point where a string does not matching pattern start at the beginning of the string Match the lookup string. This is a non-fetch match, which means that the match does not need to be acquired for later use. For example ' Windows (?! 95|98| nt|2000) ' can match Windows 3.1 ', but does not match Windows 2000 in Windows. Pre-checking does not consume characters, that is, after a match occurs, the next matching search starts immediately after the last match, rather than starting with the character that contains the pre-check.

/^[\u4e00-\u9fa5]{2,4}$/g//Match 2-4 characters

/^\w{6,18}$///matches 6 to 18 characters (letters, numbers, underscores)

/<\/? [^>]*>/GM//Match HTML tags

/(^\s*) | (\s*$)/g//match the left and right spaces

/\b ([a-z]+) \1\b/gim//matches two contiguous spaces separated by the same word, ' \1 ' is used to specify the first sub-match

/\bcha///Match the first three characters of the word ' Chapter '

/ter\b///Match ' ter ' in the word ' Chapter '

/\bapt///Matches ' apt ' in ' Chapter ', but does not match ' apt ' in ' aptitude '

Methods of regular expressions

1. Test method

Returns a Boolean value that indicates whether a pattern exists in the string being looked up.

var url= "http://msdn.microsoft.com:80/scripting/default.html?search=abc&name=xiaoming#page=1";
var reg=/(\w+): \/\/([^\/:]+) (: \d*)? (\/[^?#]*)? (\? [^\/#]*)? (#.*)?/;
var flag=reg.test (URL);
Flag//return True
REGEXP.$1//return "http"
Regexp.$2//Return to "msdn.microsoft.com"
Regexp.$3//return ": 80"
Regexp.$4//Return to "/scripting/default.html"
REGEXP.$5//return "? Search=abc&name=xiaoming"
regexp.$6//return "#page = 1"

Neither the search nor the test methods can update the global RegExp object, so regexp.input,regexp.index,regexp.lastindex returns undefined.

2. Match method

Use the regular expression pattern to perform a lookup on a string and return the result that contains the lookup as an array.

Returns null if no match is found for the match method. If a match is found, an array is returned and the properties of the global RegExp object are updated to reflect the matching results.

The array returned by the match method has two properties: Input, index (none if global match).
The input property contains the entire string that is being looked up.
The Index property contains the position of the substring that matches the entire searched string.

If the global flag (g) is not set, the 0 element of the array contains the entire match, and the 1th to n element contains the any sub-match that has occurred in the match. This is equivalent to an Exec method that does not have a global flag set. If the global flag is set, elements 0 through n contain all matches.

EXAMPLE1 (no global flag set)

var str= "USER1TESTUSER2DSFSD";
var reg=/user\d/;
var arr=str.match (REG);
ARR//Return to "user1",
ARR[0]//Return to "user1"
ARR[1]//return to undefined because there are no sub-matches here
Arr.input//Return to "USER1TESTUSER2DSFSD"
Arr.index//Return 0

Example2 (global flag set)

var str= "USER1TESTUSER2DSFSD";
var reg=/user\d/g;
var arr=str.match (REG);
ARR//Return to "User1,user2"
ARR[0]//Return to "user1"
ARR[1]//Return to "User2"
Arr.input//Return to "undefined"
Arr.index//Return to "undefined"
Note the difference after setting the global flag:
If the global flag (g) is not set, the 0 element of the array contains the entire match, and the 1th to n element contains any sub- matches that have occurred in the match.
This is equivalent to an Exec method that does not have a global flag set. If the global flag is set, elements 0 through n contain all matches.

3. Exec method

Runs a lookup in a string with a regular expression pattern and returns an array containing the results of the lookup.

If the Exec method does not find a match, it returns NULL. If it finds a match, the Exec method returns an array and updates the properties of the global RegExp object to reflect the matching results. The array returned by the Exec method has two attributes (same as the match method without g), which is input, index (lastindex can be obtained by Regexp.lastindex). The 0 elements of the array contain a complete match, and the 1th to n elements contain any one of the occurrences of a match . This is equivalent to the match method without setting the global flag (g).

If the global flag is set, it will begin retrieving string strings at the character specified by the LastIndex property of Regexpobject. When exec () finds text that matches the expression, it sets the Regexpobject LastIndex property to the next position of the last character of the matched text after the match.

If the global flag is not set, Exec ignores the value of lastindex and starts the search from the beginning of the string. We can iterate through all the matching text in the string by calling the Exec () method repeatedly. When exec () can no longer find a matching text, it returns null and resets the LastIndex property to 0.

Tip: Note that exec () adds complete details to the array it returns, regardless of whether the regexpobject is a global mode. This is where EXEC () differs from String.match (), which returns much less information in global mode. So we can say that calling the Exec () method repeatedly in a loop is the only way to get complete pattern matching information for the global schema.

EXAMPLE1 (no global flag set)
var str= "USER1TESTUSER2DSFSD";
var reg=/user\d/;
var arr=reg.exec (str);
ARR//Return to "user1",
ARR[0]//Return to "user1"
ARR[1]//return undefined, because there is no sub-match, but also through the regexp. $n to get
Arr.input//Return to "USER1TESTUSER2DSFSD"
Arr.index//Return 0

You can see that the match method is the same as the Exec method when the global flag (g) is not set.

Example2 (set global flag)
var str= "USER1TESTUSER2DSFSD";
var reg=/user\d/g;
var arr=reg.exec (str);
var arr1=reg.exec (str);
ARR//Return to "user1",
ARR1//Return to "User2",


4. Search method

Returns the position of the first substring that matches the regular expression find content.

The search method indicates whether there is a corresponding match. If a match is found, the search method returns an integer value indicating the offset from the beginning of the match distance string. If no match is found, 1 is returned.

Example1:

var str= "DFSUSER1TESTUSER2DSFSD";
var reg=/user\d/g;
var arr=str.search (REG); Returns 3

Neither the search nor the test methods can update the global RegExp object, so regexp.input,regexp.index,regexp.lastindex returns undefined.

5. Replace method

Returns the copy of a string after a literal substitution based on a regular expression

The global RegExp object can be updated to return the position of the first substring that matches the regular expression find content.

Parameter M

Additional parameter m indicates that multiple lines can be matched, but this only works when using the ^ and $ patterns, and in other modes, a multiline match can be made without adding m (i.e. a multiline string is also a normal string).

Example1:

var regx=/user\d/;
var str= "Sdfsfsdfsdf
Sdfsuser3 dffs
B76DSF User6 ";
var rs=str.match (REGX);
Without the parameter G at this time, return {User3}, add parameter G to return {USER3,USER6}, add not to M does not affect this.

Example2:
var regx=/^b./;
var str= "Ret76 Dfsdf
Bjfsdfs dffs
B76DSF SDFSDF ";
var rs=str.match (REGX);
At this point, the value of RS is null, if the value added to G,rs is still null, if added m, then the value of RS is {BJ} (that is, there is no match in the first row, because there is a parameter m, so you can continue to go to the following line to find if there is a match), if M and G are added, (only m does not add the G description, can go to multiple lines to match, but found a match to return, adding g to indicate that all the matches in multiple rows returned, of course, for the match method, for the exec, you need to execute several times to return).

JavaScript Regular Expression notes

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.