JavaScript Regular Common Knowledge summary

Source: Internet
Author: User

First, JavaScript regular correlation method

Str.match (RegExp) functions similarly to regexp.exec (str).

Str.search (RegExp) functions similarly to regexp.test (str).

1. String.prototype.match ()

Retrieves a match and returns an array (no g) that matches the first full substring and the capture result of the captured group below it, or returns all full substrings of the match (with G)

Grammar
str.match(regexp)
Param
    • RegExp: A regular Expression object. If a non-regular expression object is passed in, it is implicitly converted to a REGEXP using new RegExp (obj).
Return
    • If the regular expression does not contain the G flag: An array is returned, the first item of the array is matched with the complete string, and the following item is the result of the captured parentheses; The array also contains an index property whose value is the index of the full string in the match result in the original string The array also contains an input property whose value is the original string. The result returned at this time is exactly the same as the result returned by Regexp.exec ().

    • If the regular expression contains the G flag: Returns an array that contains all matching full substrings, but does not contain a matching capturing group capture result, nor the index property and the input property.

    • If a regular expression is provided but does not match (with or without g): returns null

    • If no arguments are supplied, use match () directly: Returns an array containing an empty string: [""], and the array also contains the Index property as the 0,input property as the original string.

Example 1: Regular expression with no g, with capturing group, and only one complete match
var str = ‘For more information, see Chapter 3.4.5.1‘;var reg = /see (chapter \d+(\.\d)*)/i;var result = str.match(reg);/* result:[   "see Chapter 3.4.5.1",   "Chapter 3.4.5.1",   ".1",   index: 22,   input: "For more information, see Chapter 3.4.5.1", groups: undefined]*/// ‘see Chapter 3.4.5.1‘ 是整个匹配。// ‘Chapter 3.4.5.1‘ 被‘(chapter \d+(\.\d)*)‘捕获。// ‘.1‘ 是被‘(\.\d)‘捕获的最后一个值。// ‘index‘ 属性(22) 是整个匹配从零开始的索引。// ‘input‘ 属性是被解析的原始字符串。
Example 2: Regular expression with G, with capturing group, and only one complete match
var str = ‘For more information, see Chapter 3.4.5.1‘;var reg = /see (chapter \d+(\.\d)*)/ig;var result = str.match(reg);/* result:[  "see Chapter 3.4.5.1"]*/
Example 3: Regular expression with G, without capturing group, with multiple complete matches
var str = ‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz‘;var regexp = /[A-E]/gi;var result = str.match(regexp);/* result:["A", "B", "C", "D", "E", "a", "b", "c", "d", "e"]*/
Example 4: Regular expression with G, with capturing group, with multiple complete matches
var str = ‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz‘;var regexp = /A(BCD)*/gi;var result = str.match(regexp);/* result:["ABCD", "abcd"]*/
Example 5: Do not pass parameters
var str = ‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz‘;var result = str.match();/* result:[  "",   index: 0,   input: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",   groups: undefined  ]*/
2. RegExp.prototype.exec ()

Performs a search match in a specified string. Returns an array of results or null. The properties of the regular expression object are updated.

Grammar
regExp.exec(str)
Param
    • STR: string to match regular expression
Return
    • If the match succeeds: An array is returned, the first item of the array is to match the complete string, and the following item is the result of the captured parentheses; The array also contains an index property whose value is the index of the complete string in the matching result in the original string, and the array contains a The input property , whose value is the original string.

    • If the match fails: the Exec () method returns NULL.

The returned result is exactly the same as the result returned in Str.match (RegExp) with a regexp without G.

Updates to the regular Expression object properties

An update to the original regular expression object is made for the following properties:

    • LastIndex: The position at which the next match begins. is the index of the next character after matching the complete string. When a regular object contains "G", the Exec method can be executed multiple times on the same regular object to find multiple successful matches in the same string. The lookup starts at the location specified by the LastIndex property of the regular expression.
    • IgnoreCase: Whether the "I" tag is used to make the regular match ignore case
    • Global: Whether the "G" tag is used to match globally.
    • Multiline
      Whether the "M" tag is used to make the regular work in multiline mode (that is, ^ and $ can match the start and end of each line in the string (the line is split by \ n or \ r), not just the beginning and end of the entire input string. )
    • Source: string of regular expression (without IgM tag)
Example 1
var regexp = /quick\s(brown).+?(jumps)/ig;var str = ‘The Quick Brown Fox Jumps Over The Lazy Dog, quick brown jumps‘;var result1 = regexp.exec(str);/* result1:[  "Quick Brown Fox Jumps",   "Brown",   "Jumps",   index: 4,   input: "The Quick Brown Fox Jumps Over The Lazy Dog, quick brown jumps",   groups: undefined]*/// regexp:regexp.lastIndex;//25 (即Jumps后面的那个空格符)regexp.ignoreCase;//trueregexp.global;//trueregexp.multiline;//falseregexp.source;//"quick\s(brown).+?(jumps)"var result2 = regex.exec(str);//result2:/* [  "quick brown jumps",   "brown",   "jumps",   index: 45,   input: "The Quick Brown Fox Jumps Over The Lazy Dog, quick brown jumps",   groups: undefined]*///regexp:regexp.lastIndex;//62regexp.ignoreCase;//trueregexp.global;//trueregexp.multiline;//falseregexp.source;//"quick\s(brown).+?(jumps)"
3. String.prototype.search ()

Performs a search match between the regular expression and the string. Returns the first full-match index in a string or-1.

Grammar
str.match(regexp)
Param
    • RegExp: A regular Expression object. If a non-regular expression object is passed in, it is implicitly converted to a regular expression object by using new RegExp (obj).
Return
    • If the match succeeds: Returns the index of the first full match of the regular expression in the string.
    • If the match fails: returns-1.
Example 1:
var str = ‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz‘;var regexp = /A(BCD)*/gi;str.search(regexp); //0
4. RegExp.prototype.test ()

Performs a search to see if the regular expression matches the specified string. Returns TRUE or FALSE.

Grammar
regexp.test(str)
Param
    • STR: A string used to match a regular expression
Return

The type Boolean. Returns true if the regular expression matches the specified string, otherwise false.

5. String.prototype.replace

Returns a new string that replaces some or all of the matching patterns with a replacement value. A pattern can be a string or a regular expression, and the replacement value can be a string or a function to be called every time a match is used. The original string does not change

Grammar
str.replace(regexp|substr, newSubStr|function)
Params
    • Pattern
      • RegExp: A RegExp object or regexp literal. The contents of the regular match are replaced by the return value of the second parameter.
      • SUBSTR: a string. It is replaced by the return value of the second parameter, because the SUBSTR is treated as a string rather than a regular, so only the first match is replaced.
    • Replacement:
      • NEWSUBSTR: A string used to replace the matching part of the first argument in the original string. Some special variable names can be interpolated into the string.
      • Functions: A function that creates a new substring, and the return value of the function replaces the result that the first argument matches.

Special variable names that can be inserted in the NEWSUBSTR:

Variable name represents a value
$$ $
$& Matched Sub-string
$` Content to the left of the currently matched substring
$ Content to the right of the currently matched substring
$n n is a positive integer if the first parameter of the replace () method is RegExp, which indicates the matching result of the nth capturing group

Parameters of function:

Variable name represents a value
Match Matches the substring. (corresponds to the above $&.) )
P1,P2,.. If the first parameter of the replace () method is a regexp, it represents the matching result of the nth capturing group. (corresponds to the above $1,$2 and so on.) )
Offset The offset of the substring matched to the original string. (for example, if the original string is "ABCD", the substring matched to is "BC", then this parameter will be 1)
String The original string that was matched.
Return

Matches the new string after replacement. The original string does not change.

Example 1: Replacing a regular match result with a function
function replaceFunc(match, p1, p2, p3, offset, string) {  return [p1, p2, p3].join(‘-‘);}var str = ‘abc12345#$*%‘;var result = str.replace(/([^\d]*)(\d*)([^\w]*)/, replaceFunc)//"abc-12345-#$*%"
Example 2: Replacing a regular with the G flag
var str = ‘Apples are round, and apples are juicy.‘; var result = str.replace(/apples/ig, ‘oranges‘);//‘oranges are round, and oranges are juicy‘.
Example 3: Reorganizing multiple substrings in a string
var str = ‘John Smith‘;var result = str.replace(/(\w+)\s(\w+)/,‘$2 and $1‘);//‘Smith and John‘
Example 4: Converting Fahrenheit temperature to the corresponding Celsius temperature
function f2c(x){  function convert(str, p1, offset, s)  {    return ((p1-32) * 5/9) + "C";  }  var s = String(x);  var test = /(\d+(?:\.\d*)?)F\b/g;  return s.replace(test, convert);}
Example 5: String to go before and after spaces Classic! & commonly used!
str.replace(/^\s+|\s+$/g, "");
Second, commonly used matching characters 1. Character categories
character meaning
. Matches any single character except \ n \ r \u2028 or \u2029
\d Match any Arabic numerals. equivalent to [0-9]
\d Matches any character that is not an Arabic numeral. equivalent to [^0-9]
\w Matches any number letter underline. equivalent to [a-za-z0-9_]
\w Matches any character that is not a numeric letter underline. equivalent to [^a-za-z0-9]
\s Matches a white space character, including spaces, tabs, page breaks, line feeds, and carriage returns that conform to other Unicode spaces. equivalent to [\T\F\N\R\V\U00A0, etc.]
\s Match a non-whitespace character
\ t Match a horizontal tab (tab)
\ r Match a return character (carriage return)
\ n Match a line break (linefeed)
\v Match a vertical tab (vertical tab)
\f Match a page break (form-feed)
[\b] Match a BACKSPACE (BACKSPACE) (do not confuse with \b)
2. Borders
character meaning
^ The match input starts. When there is an M flag, the start and end characters (^ and $) are considered to work on multiple lines (that is, match the start and end of each line separately (by \ n or \ r), not just the beginning and end of the entire input string.
$ Matches the end of the input. When there is an M flag, the start and end characters (^ and $) are considered to work on multiple lines (that is, match the start and end of each line separately (by \ n or \ r), not just the beginning and end of the entire input string.
\b Matches a 0 wide word boundary, such as between a letter and a space. (not to be confused with [\b]). For example,/\bno/matches "no" in "at noon" and/ly\b/matches "ly" in "possibly yesterday."
\b Matches a 0-wide non-word boundary, such as between two letters or two spaces. For example,/\bon/matches ' on ' in Noon ' on,/ye\b/matches ye in ' possibly yesterday '.
3. Assertions
character meaning
X (? =y) Matches only the x that is followed by Y. Y can be any combination of regular characters.
X (?! Y Matches only x that is not followed by Y. Y can be any combination of regular characters. As an example,/\d+ (?!.) /only matches numbers that are not followed by a dot (.).
Three. Verify common regular Expressions 1. Mailbox

Simplified version:

 /\[email protected]\S+\.\S+/

Complex version:

/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/
2. User Name

User name Regular, 4 to 16 digits (letters, numbers, underscores, minus signs)

/^[a-zA-Z0-9_-]{4,16}$/
3. Password to meet certain strength

Minimum 6 digits, including at least 1 uppercase letters, 1 lowercase characters, 1 digits, one special character:

/^.*(?=.{6,})(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[[email protected]#$%^&*? ]).*$/

Check if a password meets this strength:

var pattern=/^.*(?=.{6,})(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[[email protected]#$%^&*? ]).*$/;pattern.test(‘Ftc0615!#%^‘)//true
4. Mobile phone number Regular
/^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\d{8}$/
5. Regular ID Card number
/^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
Iv. grouping and capturing parentheses

The brackets are divided into capturing grouping brackets , and two types of non-capturing brackets that are used only for grouping .

1. Capturing/grouping brackets: (...)

Ordinary parentheses with no special meaning usually have two functions: grouping and capturing.

The number of the captured brackets is calculated from left to right in the order in which the parentheses are opened .

If a reverse reference is provided, the text that matches the subexpression within these parentheses can be referenced in the later part of the expression using $, $.

2. Bracket/non-capturing brackets only for grouping: (?: ...)

Parentheses that are used only for grouping cannot be used to extract text, but can only be used to specify the object of a multi-select structure or quantifier.

They are not numbered in terms of $.

Example:

    (1|one)(?:and|or)(2|two)

After such a match, $1 or ' one ' contains ' 2 ' or ' one '

Resources

Https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/RegExp
Https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/match
Https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec
Https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/search
Https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
Https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/replace

Https://www.jb51.net/article/115170.htm

"Mastering Regular Expressions"

JavaScript Regular Common Knowledge summary

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.