Introduction to the usage of JS regular expressions

Source: Internet
Author: User
Tags regular expression uppercase letter

Brief introduction

In short, regular expressions are a powerful tool that can be used for pattern matching and substitution. Its role is as follows:

Tests a pattern of a string. For example, you can test an input string to see if there is a phone number pattern or a credit card number pattern in the string. This is known as data validation.

Replaces text. You can use a regular expression in your document to identify specific text, and then you can delete it all, or replace it with another text.

Extracts a substring from a string based on pattern matching. Can be used to find specific text in text or input fields.

Basic syntax

After a preliminary understanding of the function and function of regular expressions, let's take a look at the syntax format of regular expressions.

Regular expressions are generally as follows:

The part of the/love/where the "/" delimiter is located is the pattern that will match in the target object. The user simply puts the pattern content that wants to find the matching object in between the "/" delimiters. Regular expressions provide specialized "meta characters" to enable users to customize schema content more flexibly. The term "metacharacters" refers to those special characters that have special meaning in regular expressions and can be used to specify the mode in which the leading character (that is, the character at the front of the metacharacters) appears in the target object.

The more commonly used meta characters include: "+", "*", and "?".

The "+" metacharacters specify that its leading characters must appear consecutively or repeatedly in the target object.

The "*" Meta character stipulates that its leading characters must appear 0 or more times in the target object.

“?” Metacharacters specify that its leading object must appear 0 or one consecutive times in the target object.

Next, let's look at the specific application of regular expression meta characters.

/fo+/because the preceding regular expression contains a "+" metacharacters, it means that a string of one or more letters O can be matched with the "fool", "fo", or "football" in the target object after the letter F.

/eg*/because the preceding regular expression contains a "*" metacharacters, the representation can match a string of 0 or more letters G in the target object, such as "Easy", "ego", or "egg", after the letter E.

/wil?/because the "?" is included in the above regular expression. Metacharacters, which indicates that a string of 0 or more letters L can be matched to the "Win" or "Wilson" in the target object, and so on, followed by the letter I.

Sometimes you don't know how many characters to match. To accommodate this uncertainty, regular expressions support the concept of qualifiers. These qualifiers can specify how many times a given component of a regular expression must appear to satisfy a match.

{n} n is a non-negative integer. Matches the determined 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* '.

{n,m} m and n are non-negative integers, where n <= m. Matches n times at least and matches up to M times. For example, "o{1,3}" will match the first three o in "Fooooood". ' o{0,1} ' is equivalent to ' o '. Notice that there is no space between the comma and the two number.

In addition to metacharacters, users can specify exactly how often a pattern will appear in a matching object. For example,/jim {2,6}/The regular expression above stipulates that the character M can appear consecutively 2-6 times in a matching object, so the regular expression above can match a string such as Jimmy or Jimmmmmy.

After a preliminary understanding of how to use regular expressions, let's look at how other important metacharacters are used.

S: Used to match a single spaces, including tab keys and line breaks;

S: Used to match all characters except a single spaces;

D: Used to match numbers from 0 to 9;

W: Used to match letters, numbers or underscore characters;

W: used to match all characters that do not match w;

. : Used to match all characters except for line breaks.

(Note: We can think of S and S and W and W as inverse)

Below, let's take a look at how to use the above metacharacters in regular expressions.

/s+/the above regular expression can be used to match one or more whitespace characters in the target object.

/d000/If we have a complex financial statement in hand, then we can easily find all sums up to thousand dollars through the regular expressions mentioned above.

In addition to the meta characters we have described above, there is another unique special character in the regular expression, that is, the locator. The locator character is used to specify where the match pattern appears in the target object. The more commonly used locator characters include: "^", "$", "B" and "B".

The "^" locator stipulates that the match pattern must be present at the beginning of the target string

The "$" locator stipulates that the matching pattern must be present at the end of the target object

The "B" locator stipulates that the matching pattern must now be one of the two boundaries at the beginning or end of the target string

The "B" locator stipulates that the matching object must be within the two boundaries at the beginning and end of the target string,

That is, the matching object can neither be the beginning of the target string nor the end of the destination string.

Similarly, we can think of "^" and "$" and "B" and "B" as two sets of locators that are reciprocal operations. For example:/^hell/because the above regular expression contains a "^" Locator, you can match a string that starts with "hell", "Hello", or "Hellhound" in the target object. /ar$/because the above regular expression contains a "$" locator, you can match a string that ends with "car", "bar", or "AR" in the target object. /bbom/because the above regular expression pattern starts with a "B" locator, it can match a string that starts with "bomb" or "BOM" in the target object. /manb/because the above regular expression pattern ends with a "B" locator, you can match a string that ends with "human", "Woman", or "man" in the target object.

In order to make it easier for users to set a matching pattern, regular expressions allow the user to specify a range in the matching pattern and not be limited to specific characters. For example:

/[a-z]/the above regular expression will match any uppercase letter from a to Z range.

/[a-z]/the above regular expression will match any lowercase letter from a to Z range.

/[0-9]/the above regular expressions will match any number in the range 0 through 9.

/([a-z][a-z][0-9]) +/the above regular expression will match any string of letters and numbers, such as "aB0".

The point to note here is that you can use "()" to group strings together in regular expressions. The "()" symbol contains content that must also appear in the target object. Therefore, these regular expressions will not match strings such as "ABC", because the last character in "ABC" is a letter rather than a number.

If we want to implement a "or" operation in a regular expression that is similar in programming logic, you can use the pipe character "|" If you choose one of several different modes to match. For example:/to|too|2/the above regular expression will match "to", "too", or "2" in the target object.

There is also a more commonly used operator in the regular expression, that is, the negative character "[^]". Unlike the locator "^" described in the previous article, the negative character "[^]" stipulates that the string specified in the pattern cannot exist in the target object. For example:/[^a-c]/the above string will match any character except A,b, and C in the target object. Generally, when "^" appears inside "[]", it is regarded as a negation operator, and when "^" is outside "[]" or there is no "[]", it should be treated as a locator character.

Finally, the escape character "" is used when the user needs to add metacharacters to the pattern of regular expressions and find their matching objects. For example:/th*/The regular expression above will match the "th*" in the target object rather than the "the".

After a regular expression is constructed, it can be evaluated like a mathematical expression, that is, it can be evaluated from left to right and in order of precedence. Priority is as follows:

1. Escape character

2. (), (?:), (? =), [] parentheses and square brackets

3.*, +,?, {n}, {n,}, {n,m} qualifier

4.^, $, anymetacharacter position and order

5.| " or the action

Working with instances

With a powerful regexp () object in JavaScript 1.2, you can use a matching operation for regular expressions. The test () method can verify that the target object contains a match pattern and returns TRUE or false accordingly.

We can use JavaScript to write the following script to verify the validity of the email address entered by the user.

Regular Expression Object

This object contains regular expression patterns and flags that indicate how patterns are applied.

Syntax 1 re =/pattern/[flags]

Syntax 2 re = new RegExp ("pattern", ["flags"])

Parameters

Re

Required option. The name of the variable that will be assigned the regular expression pattern.

Pattern

Required option. The regular expression pattern to use. If Syntax 1 is used, the pattern is separated by the "/" character. If you use Syntax 2, enclose the pattern in quotation marks.

Flags

Options available. If you use Syntax 2, enclose the flag in quotation marks. Flags can be used in combination, available in:

G (all occurrences of pattern in full text search)

I (Ignore case)

m (Multiple-line lookup)

Example

The following example creates an object (re) that contains a regular expression pattern and associated flags to show you the use of the regular Expression object. In this case, the regular expression object that is the result is also used in the match method:

. The code is as follows:

function Matchdemo ()

{

var r, re; Declare a variable.

var s = "The rain in Spain falls mainly in the plain";

Re = new RegExp ("Ain", "G"); Creates a regular expression object.

r = S.match (re); Finds a match in the string s.

return (R);

}

If the above content is still not enjoyable, it is recommended that you look at the regular expression of the 30-minute introductory course, easier to start and learn.

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.