Learning JavaScript-Regular Expressions

Source: Internet
Author: User

I have encountered a lot of problems when using regular expressions today. I have studied it and made reference to many blogs. For details about the parameters of a regular expression, refer to/I (case-insensitive)/g (all matching characters in full-text search)/m (multi-row search)/gi (full-text search, case-insensitive) /ig (full-text search, case-insensitive) characters in I mode will match uppercase/lowercase letters at the same time m strings will be considered as multiple lines s strings will be considered as single lines, the line break is used as the normal character x to ignore the blank space in the mode. The e preg_replace () function replaces the reverse reference in the replacement string and uses it as the PHP code to evaluate the value, replace the searched string with the result. A forces match $ metacharacters in D mode only starting from the start of the target string U match the end of the target string u match the nearest string U mode string is treated as A UTF-8 using A regular expression method reference W3SchoolRegExp the object has three methods: test (), exec (), and compile (). You can create a RegExp object in either of the following ways. Var re = new RegExp ("a", "gi"); // match all a or A var re =/a/gi; // The same as the previous RegExp Object Property describes whether the global RegExp object has a flag. Whether the ignoreCase RegExp object has flag I. LastIndex is an integer that indicates the next matching character position. Whether the multiline RegExp object has a flag m. Source Text of the source regular expression. RegExp object method description compile compilation regular expression. Exec retrieves the value specified in the string. Return the value found and locate it. Test retrieves the value specified in the string. Returns true or false. The String object has four methods: search (), match (), replace (), and split (). The method used to describe the String object that supports regular expressions to search for values that match regular expressions. Match finds matching of one or more regular expressions. Replace replaces the substring that matches the regular expression. Split splits the string into a string array. Test () RegExpObject. test (string) string is required. Is the string to be detected. If the string contains the text that matches RegExpObject, true is returned; otherwise, false is returned. Call the test () method of RegExp object r and pass the string s for it. It is equivalent to this representation: (r.exe c (s )! = Null ). Var patt1 = new RegExp ("e"); patt1.test ("CraryPrimitiveMan"); because the character string contains the letter "e", the result is true exec () this method is used to retrieve the matching of regular expressions in a string. RegExpObject.exe c (string) string is required. Is the string to be detected. Returns an array containing matching results. If no match is found, the return value is null. The exec () method is very powerful. It is a common method, and it is more complicated to use than the test () method and the String object method that supports regular expressions. If exec () finds the matched text, an array of results is returned. Otherwise, null is returned. The first element of this array is the text that matches the regular expression, and the second element is the text that matches the 0th subexpression of RegExpObject (if any ), the 2nd elements are texts that match the 2nd sub-expressions of RegExpObject (if any), and so on. In addition to the array element and length attribute, the exec () method returns two attributes. The index attribute declares the position that matches the first character of the text. The input attribute stores the retrieved string. We can see that when calling the exec () method of a non-Global RegExp object, the returned array is the same as the array returned by calling the String. match () method. However, when RegExpObject is a global regular expression, the behavior of exec () is slightly more complex. It will start searching string at the character specified by the lastIndex attribute of RegExpObject. When exec () finds the text that matches the expression, it sets the lastIndex attribute of RegExpObject to the next position that matches the last character of the text. This means that you can call the exec () method repeatedly to traverse all matched texts in the string. When exec () can no longer find the matching text, it returns null and resets the lastIndex attribute to 0. Var patt1 = new RegExp ("e" character patt1.exe c ("CraryPrimitiveMan"); because the character string contains the letter "e", the result is e. You can add the second parameter to the RegExp object to set the search. For example, you can use the "g" parameter ("global") if you want to find all the characters that exist "). When the "g" parameter is used, exec () works as follows: Find the first "r" and store its location if you run exec () Again (), search from the storage location, find the next "r", and store its location var patt1 = new RegExp ("r", "g "); do {result = patt1.exec ("CraryPrimitiveMan"); console. log (result);} while (result! = Null) because the string contains three "r" letters, the output of the Code is r null compile () method used to change RegExp. Compile () can either change the search mode or add or delete the second parameter. RegExpObject. compile (regexp, modifier) regexp is a regular expression. Modifier indicates the matching type. "G" is used for global matching, "I" is used for case-sensitive, and "gi" is used for global case-sensitive matching. Var patt1 = new RegExp ("e"); console. log (patt1.test ("CraryPrimitiveMan"); patt1.compile ("d"); console. log (patt1.test ("CraryPrimitiveMan"); because "e" exists in the string but no "d" exists, the result of the Code is true false search () this method is used to retrieve the specified substring in a string or a substring that matches a regular expression. StringObject. search (regexp) regexp can be a substring to be retrieved in stringObject or a RegExp object to be retrieved. Returns the starting position of the first substring matching regexp in stringObject. If no matched substring is found,-1 is returned. The search () method does not perform global match. It ignores the flag. It also ignores the lastIndex attribute of regexp and always searches from the start of the string, which means it always returns the first matching position of stringObject. Var str = "Visit W3School! "Console. log (str. search (/W3School/) returns 6 results. The match () method can be used to retrieve the specified value in a string, or to find a match between one or more regular expressions. This method is similar to indexOf () and lastIndexOf (), but it returns the specified value rather than the position of the string. StringObject. match (searchvalue) stringObject. match (regexp) searchvalue indicates the string value to be retrieved. Regexp is the RegExp object that specifies the pattern to be matched. If this parameter is not a RegExp object, you must first pass it to the RegExp constructor and convert it to a RegExp object. Returns an array of matching results. The content of this array depends on whether regexp has a global flag. The match () method retrieves the stringObject string to find one or more texts that match regexp. The behavior of this method depends largely on whether regexp has a flag. If regexp does not mark g, the match () method can only perform one match in stringObject. If no matching text is found, match () returns null. Otherwise, it returns an array containing information related to the matched text it finds. The 0th elements in the array store the matching text, while the remaining elements store the text that matches the regular expression's subexpression. In addition to these regular array elements, the returned array also contains two object attributes. The index attribute declares the position of the starting character of the matching text in the stringObject, And the input attribute declares the reference to the stringObject. If regexp has a flag, the match () method performs a global search and finds all matching substrings in stringObject. If no matched substring is found, null is returned. If one or more matched substrings are found, an array is returned. However, the content of the array returned by global match is very different from that returned by the former. Its array elements store all matched substrings in stringObject, and there is no index or input attribute. Note: In global search mode, match () does not provide text information that matches the subexpression, nor declare the position of each matched substring. You can use RegExp.exe c () to retrieve global information (). Var str = "1 plus 2 equal 3" console. log (str. match (/\ d +/g) Returns ["1", "2", "3"], which is an array. The replace () method is used to replace other characters with some characters in a string, or to replace a substring that matches a regular expression. StringObject. replace (regexp/substr, replacement) regexp/substr is the specified substring or RegExp object of the pattern to be replaced. Note that if the value is a string, it is used as the direct text mode to be retrieved, rather than being converted to a RegExp object first. Replacement is a string value. Specifies the function for replacing text or generating replacement text. Returns a new string, which is obtained after the first match or all matches of regexp are replaced by replacement. The replace () method of the string stringObject performs the search and replace operation. It searches stringObject for substrings that match regexp and replaces them with replacement. If regexp has a global flag, the replace () method replaces all matched substrings. Otherwise, it only replaces the first matched substring. Replacement can be a string or a function. If it is a string, each match will be replaced by a string. However, the $ character in replacement has a specific meaning. As shown in the following table, it indicates that the string obtained from pattern matching will be used for replacement. Replace the text $1, $2,..., $99 with the text that matches the 1st to 99th subexpressions in regexp. $ & A substring that matches regexp. $ 'Text on the left of the matched substring. $ 'Text on the right of the matched substring. $ Directly calculates the number of symbols. ECMAScript v3 stipulates that the replacement parameter of the replace () method can be a function rather than a string. In this case, each match calls this function, and the string it returns will be used as the replacement text. The first parameter of this function is a matching string. The following parameter is a string that matches the subexpression in the pattern. There can be 0 or more such parameters. The following parameter is an integer that declares the position where the matching occurs in the stringObject. The last parameter is stringObject itself. Var str = "Visit Microsoft! "Console. log (str. replace (/Microsoft/," W3School ") returns Visit W3School !. The split () method is used to split a string into a string array. StringObject. split (separator, howator) separator is a string or regular expression that separates stringObject from the specified place. How is the maximum length of the returned array that can be specified. If this parameter is set, no more substrings are returned than the array specified by this parameter. If this parameter is not set, the entire string is split, regardless of its length. Returns an array of strings. This array is created by dividing the string stringObject into substrings at the boundary specified by separator. The strings in the returned array do not include the separator itself. However, if separator is a regular expression that contains a subexpression, the returned array contains the strings that match the subexpression (but does not include the text that matches the entire regular expression ). "2: 3: 4: 5 ". split (":") Returns ["2", "3", "4", "5"] The related symbols and descriptions of regular expressions have different styles. The following table is a complete list of metacharacters in PCRE and their behavior in the context of regular expressions. It is applicable to Perl or Python programming languages (the regular expression syntax of grep or egrep is a subset of PCRE ): character Description \ mark the next character as a special character, or a literal character, or a backward reference, or an octal escape character. For example, "n" matches the character "n ". "\ N" matches a line break. The serial "\" matches "\", and "\ (" matches "(". ^ Matches the start position of the input string. If the Multiline attribute of the RegExp object is set, ^ matches the position after "\ n" or "\ r. $ Matches the end position of the input string. If the Multiline attribute of the RegExp object is set, $ also matches the position before "\ n" or "\ r. * Matches the previous subexpression zero or multiple times. For example, zo * can match "z" and "zoo ". * Is equivalent to {0 ,}. + Match the previous subexpression once or multiple times. For example, "zo +" can match "zo" and "zoo", but cannot match "z ". + Is equivalent to {1 ,}.? Match the previous subexpression zero or once. For example, "do (es )?" It can match "do" in "do" or "does ".? It is equivalent to {0, 1 }. {N} n is a non-negative integer. Match n times. For example, "o {2}" cannot match "o" in "Bob", but can match two o in "food. {N,} n is a non-negative integer. Match at least n times. For example, "o {2,}" cannot match "o" in "Bob", but can match all o in "foooood. "O {1,}" is equivalent to "o + ". "O {0,}" is equivalent to "o *". Both {n, m} m and n are non-negative integers, where n <= m. Match at least n times and at most m times. For example, "o {1, 3}" matches the first three o in "fooooood. "O {0, 1}" is equivalent to "o ?". Please note that there must be no space between the comma and two numbers .? When this character is followed by any other delimiter (*, + ,?, The matching mode after {n}, {n ,}, {n, m}) is not greedy. The non-Greedy mode matches as few searched strings as possible, while the default greedy mode matches as many searched strings as possible. For example, for strings "oooo", "o + ?" A single "o" will be matched, and "o +" will match all "o ".. Match any single character except "\ n. To match any character including "\ n", use a pattern like "(. | \ n. (Pattern) matches pattern and obtains the matched substring. This substring is used for backward reference. The obtained match can be obtained from the generated Matches set. The SubMatches set is used in VBScript, and $0… is used in JScript... $9 attribute. To match the parentheses, use "\ (" or "\)". (?: Pattern) matches the pattern but does not obtain the matched sub-string, that is, this is a non-get match, does not store the matched sub-string for backward reference. This is useful when you use the "(|)" character to combine all parts of a pattern. For example, "industr (?: Y | ies) "is a simpler expression than" industry | industrial. (? = Pattern) Forward validation pre-query: match the search string at the beginning of any string that matches pattern. This is a non-get match, that is, the match does not need to be obtained for future use. For example (? = 95 | 98 | NT | 2000) "can match" Windows "in" Windows2000 ", but cannot match" Windows "in" Windows3.1 ". Pre-query does not consume characters, that is, after a match occurs, the next matching search starts immediately after the last match, instead of starting after the pre-query characters. (?! Pattern) is a forward negative pre-query that matches the search string at the beginning of any string that does not match pattern. This is a non-get match, that is, the match does not need to be obtained for future use. For example, "Windows (?! 95 | 98 | NT | 2000) "can match" Windows "in" Windows3.1 ", but cannot match" Windows "in" Windows2000 ". Pre-query does not consume characters, that is, after a match occurs, the next matching search starts immediately after the last match, instead of starting after the pre-query characters (? <= Pattern) the reverse direction is certainly pre-query, which is similar to positive certainly pre-query, but in the opposite direction. For example, <= 95 | 98 | NT | 2000) Windows can match Windows in 2000Windows, but cannot match Windows in 3.1Windows ". (? <! Pattern) reverse negative pre-query, similar to forward negative pre-query, but in the opposite direction. For example, "(? <! 95 | 98 | NT | 2000) Windows can match "Windows" in "3.1Windows", but cannot match "Windows" in "2000Windows ". X | y matches x or y. For example, "z | food" can match "z" or "food ". "(Z | f) ood" matches "zood" or "food ". [Xyz] character Set combination (character class ). Match any character in it. For example, "[abc]" can match "a" in "plain ". Special characters only have the special meaning of backslash \ and are used to escape characters. Other special characters, such as asterisks, plus signs, and brackets, are common characters. Escape Character ^ if it appears in the first place, it indicates the combination of negative character sets. If it appears in the middle of the string, it is only a common character. Hyphen-if it appears in the middle of the string, it indicates the character range description; if it appears in the first place, it is only a common character. [^ Xyz] combination of excluded character sets (negate. Match any character not listed. For example, "[^ abc]" can match "plin" in "plain ". [A-z] character range. Matches any character in the specified range. For example, "[a-z]" can match any lowercase letter in the range of "a" to "z. [^ A-z] The excluded character range. Matches any character that is not within the specified range. For example, "[^ a-z]" can match any character that is not in the range of "a" to "z. \ B matches a word boundary, that is, the position between a word and a space. For example, "er \ B" can match "er" in "never", but cannot match "er" in "verb ". \ B matches non-word boundaries. "Er \ B" can match "er" in "verb", but cannot match "er" in "never ". \ Cx matches the control characters specified by x. For example, \ cM matches a Control-M or carriage return character. The value of x must be either a A-Z or a-z. Otherwise, c is treated as a literal "c" character. \ D matches a numeric character. It is equivalent to [0-9]. \ D matches a non-numeric character. It is equivalent to [^ 0-9]. \ F matches a break. It is equivalent to \ x0c and \ cL. \ N matches a linefeed. It is equivalent to \ x0a and \ cJ. \ R matches a carriage return. It is equivalent to \ x0d and \ cM. \ S matches any blank characters, including spaces, tabs, and page breaks. It is equivalent to [\ f \ n \ r \ t \ v]. \ S matches any non-blank characters. It is equivalent to [^ \ f \ n \ r \ t \ v]. \ T matches a tab. It is equivalent to \ x09 and \ cI. \ V matches a vertical tab. It is equivalent to \ x0b and \ cK. \ W matches any word characters that contain underscores. It is equivalent to "[A-Za-z0-9 _]". \ W matches any non-word characters. It is equivalent to "[^ A-Za-z0-9 _]". \ Xn matches n, where n is the hexadecimal escape value. The hexadecimal escape value must be determined by the length of two numbers. For example, "\ x41" matches "". "\ X041" is equivalent to "\ x04 & 1 ". The regular expression can use ASCII encoding .. \ Num back-reference a substring (substring) that matches the nth substring of the regular expression (subexpression) enclosed by parentheses. Num is a positive integer starting from 1, and its upper limit may be 99. For example, "(.) \ 1" matches two consecutive identical characters. \ N identifies an octal escape value or a backward reference. If at least n subexpressions are obtained before \ n, n is backward referenced. Otherwise, if n is an octal digit (0-7), n is an octal escape value. \ Nm identifies an octal escape value or a backward reference. If at least one child expression is obtained before \ nm, the nm is backward referenced. If at least n records are obtained before \ nm, n is a backward reference followed by text m. If none of the preceding conditions are met, if n and m are Octal numbers (0-7), \ nm matches the octal escape value nm. \ Nml if n is an octal digit (0-3) and both m and l are octal digits (0-7), the octal escape value nml is matched. \ Un matches n, where n is a Unicode character represented by four hexadecimal numbers. For example, \ u00A9 matches the copyright symbol (©). Greedy and non-Greedy modes in the number of matches: when you use a special symbol to modify the number of matches, there are several representation methods that allow the same expression to match different times, such as: "{m, n} "," {m ,}","? "," * "," + ", The number of matching times varies with the string to be matched. This type of expressions with an indefinite number of repeat matches as many as possible during the matching process. For example, for the text "dxxxdxxxd", the expression matching result (d) (\ w +) is as follows) "\ w +" will match all characters after the first "d" "xxxdxxxd" (d) (\ w +) (d) "\ w +" will match all characters "xxxdxxx" between the first "d" and the last "d ". Although "\ w +" can match the last "d", to make the entire expression match successfully, "\ w +" can "let out" the last "d" that can be matched. It can be seen that when "\ w +" is matched, always match as many characters as possible according to its rules. Although the second example does not match the last "d", it is also used to make the entire expression match successfully. Similarly, the expressions with "*" and "{m, n}" Both match as much as possible, "? "When the expression can be matched but not matched, it is also" to match "as much as possible ". This matching principle is called the "greedy" pattern. Non-Greedy mode: Add "? "Number, the number of matching expressions can be as few as possible, so that the non-matching expressions can be matched, as far as possible" not matching ". This matching principle is called "non-greedy" mode, or "barely" mode. If there is a small match, the entire expression will fail to match. Similar to greedy mode, non-Greedy mode will be matched to a minimum to make the entire expression match successful. For example, for the text "dxxxdxxxd": expression matching result (d) (\ w + ?) "\ W +? "Match as few characters as possible after the first" d ". The result is:" \ w +? "Only matches one" x "(d) (\ w + ?) (D) To make the entire expression match successfully, "\ w +? "Must match" xxx "to make the" d "behind the expression match, so that the entire expression matches successfully. Therefore, the result is: "\ w +? Example 1: JavaScript (? :) Var x =/^ ([Jj] ava (?: [Ss] callback )?) $/, Y =/^ ([Jj] ava ([Ss] Ghost )?) $/, Z = 'javascript '; z. match (x); // The result is ["javascript", "javascript"] z. match (y); // The result is ["javascript", "javascript", "script"] Example 2: JavaScript (\ 1) var words = "This is a block of text. ", reg =/[] + (\ w +) [] + \ 1/; words. match (reg) // The result is ["of", "of"] "[] +". match one or more spaces, "\ w +" matches one or more numeric characters, while "[] +" matches spaces at the end. However, it is noted that "\ w +" is added with parentheses to make it a subexpression. This subexpression is not used for repeated matching and does not need to be repeated in this example. Here, the subexpression only groups the expression and marks the subexpression for future use. The last part of the pattern is "\ 1", which is the backward reference of the Child expression. So when "\ w +" matches the word of, "\ 1" also matches, when "\ w +" matches the word and, "\ 1" also matches and. Note: The terminology is backward applied because these entities reference previous subexpressions. But what is the actual meaning of "\ 1? It matches the first subexpression in the pattern. Similarly, "\ 2" will match the second subexpression, "\ 3" will match the fourth, and so on. "[] + (\ W +) [] + \ 1" can match all repeated words. Example 3: Code try {str = "<p> abcdefg </p> <p> abcdefghijkl </p>"; re1 = str. match (/<p> [\ W \ w] +? <\/P>/ig); console. log ("non-Greedy mode: \ r \ n \ r \ n1:" + re1 [0] + "\ r \ n2:" + re1 [1]); re1 = str. match (/<p> [\ W \ w] + <\/p>/ig); console. log ("greedy mode: \ r \ n" + re1); re1 = str. match (/<p> (. + ?) <\/P>/I); console. log ("non-Greedy mode, and do not mark: \ r \ n \ r \ n1:" + re1 [1]); re1 = str. match (/<p> (. +) <\/p>/I); console. log ("greedy mode, and do not mark: \ r \ n" + re1 [1]);} catch (e) {console. log (e. description)} copy the code running result: Non-Greedy mode: 1: <p> abcdefg </p> 2: <p> abcdefghijkl </p> greedy mode: <p> abcdefg </p> <p> abcdefghijkl </p> non-Greedy mode. Do not mark: 1: abcdefg greedy mode, and do not mark: abcdefg </p> <p> abcdefghijkl Example 4: the two returned results are different. var objReg =/^ [a-zA-Z] {1} (:) {1} $/gi; console. log (objReg. test (": "); // Return true console. log (objReg. test (" a: "); // return false. Why does the second test return false? Is it strange. Test is actually the same as the exec method, but the return value is different. Test returns true or false (if exec does not return null), exec returns pattern (matching ). While the exec execution process is: when the g parameter is included, the next matching will automatically jump to the location after lastIndex, that is, the 2nd location here. This location obviously does not match pattern. Therefore, false is returned. Solution: (1) do not use g (Global parameter) var objReg =/^ [a-zA-Z] {1} (:) {1} $/I; console. log (objReg. test ("a:"); // returns trueconsole. log (objReg. test ("a:"); // return true (2) you can use lastIndex = 0 to restore var objReg =/^ [a-zA-Z] {1} (:) {1} $/gi; console. log (objReg. test ("a:"); // returns true objReg. lastIndex = 0; console. log (objReg. test ("a:"); // return true

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.