Easily learn JavaScript 14th: JavaScript RegExp object (regular expression)

Source: Internet
Author: User

Easily learn JavaScript 14th: JavaScript RegExp object (regular expression)

1. RegExp object Overview

The RegExp object represents a regular expression. RegExp is the abbreviation of a regular expression. It is a powerful tool for matching string execution modes. RegExp

Objects are used to specify the content to be retrieved in the text. When you retrieve a text, you can use a mode to describe the content to be retrieved. RegExp

Mode. A simple mode can be a single character. A more complex mode includes more characters and can be used for parsing, format check, replacement, and so on.

A regular expression can specify the search position in a string and the type of characters to be retrieved.

2. Create a RexExp object

Creating a regular expression is similar to creating a string. There are two ways to create a regular expression:

(1) syntax for creating a RegExp object using the literal:

/Pattern/attributes;

(2) syntax for creating a RegExp object using the new Keyword:

New RegExp (pattern, attributes );

Parameter description:

1. The pattern parameter is a string that specifies the regular expression mode or other regular expressions.

2. The attributes parameter is an optional mode string that contains the attributes "g", "I", and "m", which are used to specify the global matching and case-insensitive matches, respectively.

Configuration and multi-line matching.

The RegExp object is used to store the retrieval mode. Create a RegExp object using the new keyword. The following generation creates a RegExp pair named pattern.

The pattern is "e". When this RegExp object is used to search in a string, the character "e" will be searched ".

 

Var pattern = new RegExp ("e"); var pattern = new RegExp ("e", gi); // set global search to case-insensitive

 

The above can also be created in a literal way. This method is also frequently used:

 

var pattern=/e/;var pattern=/e/gi;

 

Detailed parsing of three RegExp objects

(1) RegExp Object Attributes

We have already seen these basic examples above, but let's take a few simple examples to look:

 

Var pattern =/e/gim; document. write (pattern. global + ""); // output: true. Indicates that the global mode document is set. write (pattern. ignoreCase + ""); // output: truedocument. write (pattern. multiline + ""); // output: truedocument. write (pattern. source + ""); // output: e

 

(2) RegExp object Method

The RegExp object has three methods: test (), exec (), and compile ().

1) The test () method retrieves the specified value in the string. the return value is true or false.

 

Var pattern =/e/; var str = "The best things in life are free"; document. write (pattern. test (str); // output: true

 

2) the exec () method retrieves the specified value in the string. The returned value is the value found. If no matching is found, null is returned. Instance 1:

 

Var pattern =/e/; var str = "The best things in life are free" using document.write(pattern.exe c (str); // output: e

 

Example 2:

Add the second parameter to the RegExp object to set the search. If you need to find all the characters that exist, you can use the "g" parameter.

When the "g" parameter is used, exec () works as follows:

1. Locate the first "e" and store its location.

2. If exec () is run again, search from the storage location, find the next "e", and store its location.

 

var pattern=/e/g;var str="The best things in life are free";do{    var result=pattern.exec(str);    document.write(result+" ");}while(result!=null)

 

The output result is: e null.

3) The compile () method is used to change the regular expression. compile () can either change the search mode or add or delete the second parameter.

 

Var pattern =/e/; var str = "The best things in life are free"; document. write (pattern. test (str); // output: truepattern. compile ("d"); document. write (pattern. test (str); // output: false

 

(3) method of String object supporting regular expressions

Because regular expressions have some relationships with String objects, some methods of String objects can be used in regular expressions:

 

Var pattern =/e/g; // enable global mode var str = "The best things in life are free"; document. write (str. match (pattren) + ""); // output in the form of an array: e, edocument. write (str. search (pattren) + ""); // output: 2 (returns the first matched position) document. write (str. replace (pattren, "a") + "); // output: Tha bast things in lifa ara fraavar pattern1 =/\ s/g; // \ s indicates the space character document. write (str. split (pattren1); // output: The, best, things, in, life, are, free

 

(4) metacharacters are characters with special meanings:

As these are widely used, we just give a few examples:

 

Var pattern =/B. ue/; // The dot sign to match any character except the line break. Var str = "blue"; document. write (pattern. test (str); // output: true

 

(5) square brackets are used to find characters in a specific range:

 

Var pattern =/[a-z] oogle/; // [a-z] indicates 26 lower-case letters. Any one can match var str = "woogle"; document. write (pattren. test (str); // output: true

 

(6) quantifiers

 

Var pattern =/go + gle/; // o * Indicates matching at least one 0var str = "google"; document. write (pattren. test (str); // output: true

 

Four Common Regular Expressions

It mainly looks at the regular expression represented by the patttern string of the variable. The rest are some basic JS things that can be ignored.

(1) Check the zip code

 

Var pattern =/^ [0-9] {6} $/; // it must be a six-digit var str = prompt ("Enter the zip code: "); if (pattern. test (str) {alert ("You entered the correct zip code! ");} Else {alert (" You entered the wrong zip code! ");}

 

The running result of some input data is:

Input: 056500

Input: 123

(2) Simple email address verification

Var pattern =/^ ([\ w \. \-] +) @ ([\ w \-] + )\. ([a-zA-Z] {2, 4}) $/; var str = prompt ("Enter the email name:"); if (pattern. test (str) {alert ("You entered the correct email name! ");} Else {alert (" You entered the wrong email name! ");}
(3) Check the compressed file package

 

 

Var pattern =/[\ w] + \. zip | rar | gz/; // \ w indicates all numbers, letters, and underlines var str = prompt ("enter the name of the compressed package:"); if (pattern. test (str) {alert ("You entered the correct package name! ");} Else {alert (" You entered the wrong compressed package name! ");}
(4) Check the mobile phone number
Var pattern =/^ [1] [0-9] {10} $/; var str = prompt ("Enter your mobile phone number:"); if (pattern. test (str) {alert ("You entered the correct mobile phone number! ");} Else {alert (" You entered the wrong mobile phone number! ");}

The following three output results will not be displayed one by one. You only need to write a regular expression to check whether the input data is correct. Since we have just been in touch

The regular expression may be incorrect and will be improved and corrected by yourself.


 

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.