JavaScript Regular Expression Learning

Source: Internet
Author: User
Tags modifier

The application of regular expressions has been quite extensive, before also many contacts, but not the real system of learning, take this opportunity, a good tidy up a bit, and joined the ES6 in the regular expression of the new grammar, I hope that a little help.

First, to understand the meaning of the regular expression, the expression method

Regular expressions, also known as regular expressions, (Regular expression, often abbreviated to regex, RegExp, or re in code), a logical formula for string manipulation is to make a "rule string" with some predefined characters and combinations of these specific characters. This "rule string" is used to express a filtering logic for a string. Regular tables are often used to retrieve and replace text that conforms to a pattern (rule).

There are two ways to represent a regular expression.

A. Direct volume representation.

/pattern/attributes; //   /Regular expression body/modifier (optional)

The B.regexp object representation. In JavaScript, the RegExp object is a regular expression object that has pre-defined properties and methods.

New REGEXP (pattern,attributes);   //    Create RegExp object (regular expression body, modifier (optional))

An expression body. The expression body (pattern) is a string that specifies the pattern of the regular expression.

Modifier. The modifier (attributes) is an optional parameter that contains the attribute G (global match), I (case-insensitive match), M (Multi-line match), the Y (sticky sticky) modifier in es6, the Y modifier similar to G, and a global match. The last match starts at the next position where the last match succeeded, except that the G modifier is the same as long as there is a match in the remaining position, but the Y modifier must start at the remaining first position.

Second, the character in the regular expression.

1. Ordinary characters.

Letters, numbers, Chinese characters, underscores, and some punctuation that are not specifically defined. Most characters belong to ordinary characters, ordinary characters in regular, and match the same characters when matching the string ~ such as the following code:

var str = "ABCDE"; Console.log (Str.match (//  ["A", index:0, Input: "ABCDE"]

As in the code, the string ABCDE matches a when the match succeeds and the index position starts at 0.
2. Meta-characters.

Metacharacters Describe
. Find any single character, except line break
\w Any one letter or number or underscore, any one of the a_za_z0_9,_
\w Find characters that are not words, equivalent to [^a_za_z0_9_]
\d Matches a numeric character, equivalent to [0-9]
\d Matches a non-numeric character, equivalent to [^0-9]
\s Matches any whitespace character, including spaces, tabs, line breaks, and so on. equivalent to [\f\n\r\t\v]
\s Matches any non-whitespace character, equivalent to [^\f\n\r\t\v]
\b

Match a word boundary, that is, the position between the word and the space, such as ' er\b ' can match "never"

"ER", but does not match "er" in "verb"

\b Matches a non-word boundary, ' er\b ' can match ' er ' in ' verb ', but cannot match ' er ' in ' Never '
/

Find nul characters.

\ n Match a line break
\f Match a page break
\ r Match a carriage return character
\ t Match a tab
\v Match a vertical tab
\xxx Find a character that is specified in octal number xxx
\xdd Find the characters specified in 16 decimal dd
\uxxxx Finds the Unicode character specified in xxxx with 16 decimal digits.

3. Escape character. Special characters that need to be escaped before adding \

Third, the meaning of [], {}, () in the regular

1. []: square brackets contain a series of characters that can match any of these characters, such as

[A-Z]: Find any character from A to Z from a small write;

[^a-z]: Find any character except A to Z;

expression [BCD][BCD] matches "ABCDE" when the match succeeds, the content is BC, the match to the position starts at 1, ends with 3; The following code:

var str = "ABCDE"; Console.log (Str.match (///  ["BC", index:1, Input: "ABCDE"]

2.{}: {Where the tag qualifier begins, n{x} matches the sequence string containing the N of X.

3. (): The expression in parentheses can be modified as a whole when the number of matches is modified. When the matching result is taken, the expression in parentheses matches the content that can be obtained separately.

Four, quantifiers

n+

Match any string that contains at least one n

N

A string that matches 0 or more n

N?

Match 0 or 1 n strings

N{X}

Matches a sequence string that contains x n

N{x,y}

Matches a string of at least X, up to Y N

N{x,}

Match a string of at least X

n$

Matches a string ending in n

^n

Matches a string that begins with n

? =n

Matches the n string immediately after the specified

?! N

Match does not follow the specified n string immediately thereafter

The regular method of string

A. Match () method , which is used to retrieve the specified value within a string, or to find a match for one or more regular expressions.


Stringobject.match (RegExp)

Searchvalue needs to retrieve the value of the string; RegExp: RegExp object that needs to match the pattern. The return value holds the array of successful matches; It can match the pattern globally, and it returns an array if it is globally matched. If no match is found, it returns NULL, the returned array has three elements, the first element holds the matched text, and two object properties; The Index property indicates the position of the starting character of the matched text in the Stringobject The Input property declares a reference to a Stringobject object.

var str = "Welcome to China"; Console.log (Str.match (///  [0: "Come", Index:3, Input: "Welcome to China"]//  NULL  //  [0: "Come", Index:3, Input: "Welcome to China"]

B. Replace () method : This method is used to replace some characters with some character in a string, or to replace a substring that matches a regular expression;

Stringobject.replace (A string or RegExp object that needs to be replaced, the text or function to replace);

Returns the new string after replacement

Note: the Stringobject replace () method of the string performs a find and replace operation, replacing the pattern with 2 types, which can be either a string or a regular match pattern, if it is a regular match pattern, then it can add modifier g, which represents the global substitution, Otherwise, it replaces only the first matching string.

var str = "Welcome to China";   var s1 = str.replace ("We", "a"); Console.log (S1); // Alcome to China var s2 = str.replace (/e/, "B"//wblcometo Chinavar s3 = str.replace (/o/g , ' x '//welcxme TX China    

C. Search (). This method is used to retrieve the substring specified in the string, or to retrieve a string that matches the regular expression.

Stringobject.search (The string or RegExp object to retrieve);

The return value is the starting position of the first substring in stringobject that matches the RegExp object. If no matching substring is found, the return -1;search () method does not perform a global match, it ignores the flag g, and it does not have a property of the lastindex of the RegExp object, and always finds it from the beginning of the string. Always returns the first position of the Stringobject match.

var str = "Welcome to China,we is Family"; Console.log (Str.search (//  0

D. Split (). This method splits a string into an array of strings.

Stringobject.split (Separator,howmany);

separator[Required], a string or regular expression, where the parameter is specified to split the stringobject; howmany[Optional] This parameter specifies the maximum length of the returned array, and if this parameter is set, the returned substring will not be more than the array specified by this parameter. If this argument is not set, the entire string will be split, regardless of his length. The return value is an array of strings. The array splits the string stringobject into substrings at the boundary specified by separator.

var str = "Welcome to China,we is Family"; Console.log (Str.split (///  ["W", "lcom", "to China,w", "ar", "Family"]  console.log (str.split (//  ["W", "lcom", "to China,w"]

Vi. RegExp Object Methods

1. Test () method : This method is used to detect whether a string matches a pattern.

    Regexpobject.test (string to be detected);  Returns TRUE or False

  

1 var str = "Welcome to China,we is Family"; 2 // true 3 // false   

2.exec () Method: This method is used to retrieve the matching of regular expressions in a string.

  Regexpobject.exec (string to be detected)  //Returns an array that holds the matching result, or null if no match is found;

The first element of the returned array is the text that matches the regular expression, which also returns 2 properties, the Index property declares the position of the first character of the matched text, and the input property holds the string that is retrieved, and if the method is not global, The returned array is the same as the array returned by the match () method.

var str = "Welcome to China,we is Family"; Console.log (/come/.exec (str)); ["Come", Index:3, Input: "Welcome to China,we is Family"] Console.log (/will/.exec (str)); Null

  

    

JavaScript Regular Expression Learning

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.