Regular Expressions of the JS basic series and basic regular expressions of js

Source: Internet
Author: User
Tags string methods

Regular Expressions of the JS basic series and basic regular expressions of js

Regular Expressions are awesome. Today, they are just a simple introduction to people who are new to Javascript. If there are any disputes, please leave a message!

1.1 What is a regular expression

A regular expression is an object that describes character patterns. The RegExp class of ECMAScript represents a regular expression, both String and RegExp define functions that use regular expressions for powerful pattern matching and text retrieval and replacement.

Regular expressions are used to match and replace string modes. They are a powerful tool for matching string execution modes.

1.2 functions of a regular expression

Regular Expressions are mainly used to verify the input data of the client.

After you enter the form and click the button, the form will be sent to the server. on the server side, PHP, ASP. NET, JSP, and other server scripts will be used for further processing. Because of client verification, it can save a lot of system resources on the server side and provide a better user experience.

2. Create a regular expression ==( 123) ==

To use a regular expression, you must first create a regular expression object. There are two ways to create an object:

2.1 Method 1: create with the keyword new

var patt = new RegExp(pattern,modifiers);

Parameter 1: regular expression mode. String format

Parameter 2: Pattern modifier. Specifies global matching, case-sensitive matching, and multi-row matching.

<Script type = "text/javascript">/* creates a regular expression parameter 1: The pattern is: girl, meaning that it can match string parameter 2 like "girl: pattern modifier: gi g indicates global match I indicates case insensitive */var pa = new RegExp ("girl", "gi "); // test whether the string "Hello my girl" in the parameter matches the matching pattern. Var isExist = pa. test ("Hello my girl"); // in this example, It is matched. This string contains girl, so true alert (isExist) is returned ); // true </script>

2.2 Method 2: using a regular expression

var pa = /pattern/modifiers;

Two or more vertices represent the regular expression pattern, followed by the pattern modifier.

For example, the preceding example can be used to write var pa =/girl/gi;

Note: Both the mode and mode modifier can be added with double quotation marks or single quotation marks.

<Script type = "text/javascript"> var pa =/girl/gi; alert (pa. test ("My girl"); // true </script>

3. Regular Expression Pattern modifier = (126) =

There are three pattern modifiers in JavaScript: g I u

  1. G: indicates global. It means that a string is matched multiple times. If g is not written, it will only match once. Once the match is successful, it will not match again.
  2. I: case insensitive. It means that the matching is case insensitive.
  3. U: indicates that multiple rows can be matched.

4. Detailed explanation of the Regular Expression Method = (127) =

The common Regular Expression methods include test () and exec ()

4.1 test () method

Test (string)

  • Parameter: string to be matched
  • Return Value: true if the matching is successful, false if the matching fails.

This method is very convenient when you only want to know whether the target string matches a certain pattern, but do not need to know its text content. Therefore, the test () method is often used in the if statement.

<Script type = "text/javascript"> var pa =/girl/gi; if (pa. test ("My girl") {alert ("this girl matches you very well");} else {alert ("You are doomed to no girl match ");} </script>

4.2 exec () method

Exec (string): This method is specially designed for the capture group.

  • Parameter: string to be matched
  • Returned value: An array is returned. If no match exists, null is returned.
  • Description of the returned value array:
  • It is indeed an Array instance.
  • However, this array has two additional attributes: index and input.
  • Index: indicates the index of the matched string in the source string.
  • Input: indicates the matched source string.
  • The first item of the array is a string that matches the entire pattern, and the other items are strings that match the capture group in the pattern.
  • If no capturing group exists, only the first item in the array is displayed. Let's talk about the concept of a capture group later.
<Script type = "text/javascript"> var pa =/girl/gi; var testStr = "myGirl, yourgirl, hisgIrl"; var girls = pa.exe c (testStr ); // capture alert (girls. length + ":" + (girls instanceof Array); // The regular expression does not have a capture group, so the Array length is 1 alert (girls [0]); // Girl is captured for the first time. // because we use global match, this match starts from the position after the last match and continues matching alert(pa.exe c (testStr) [0]); // girl alert(pa.exe c (testStr); // gIrl alert(pa.exe c (testStr); // No matched string is found after the query, so return null // return nul L. If re-matching continues, it will return to the start of the string and start the rewriting to start matching. Alert(pa.exe c (testStr); // Girl //... enable a new round of matching </script>

Therefore, if we want to find all matching strings, we can use a loop. The end condition is that the matching result is null.

<Script type = "text/javascript"> var pa =/girl/gi; var testStr = "myGirl, yourgirl, hisgIrl"; var girls; while (girls = pa.exe c (testStr) {// if it is null, it is automatically converted to false and ended. Alert (girls) ;}</script>

Group. In a regular expression, tasks are enclosed in. Groups can be nested.

<Script type = "text/javascript"> // The content in () is a group of 1st girls. In fact, we can see the complete expression of 0th girls) // match the subscript of the matching result array in the future. Var pa =/girl (Girl)/gi; var test = "girlGirl abdfjla Girlgirl fal girl"; var girls; while (girls = pa.exe c (test )) {// after matching, The 0th elements in the array correspond to the matching results of The 0th groups, and the 1st elements correspond to the matching results of the 1st groups for (var I = 0; I <girls. length; I ++) {console. log (girls [I]);} console. log ("-------------") ;}</script> // The final running result: girlGirlGirl ------------- Girlgirlgirl ------------

5. Regular Expression rules = (124) =

Expression rules

The metacharacter of a regular expression is a character that contains special meanings. They have some special functions to control the matching mode.

Method. The metacharacter after the backslash will lose its special meaning.

Character class: Single Character and number

[0-9A-Za-z]
Metacharacters/metacharacters
. Match any character except linefeed
[A-z0-9] matches any character in the character set in parentheses
[^ A-z0-9] match any character in character set not in parentheses
\ D = [0-9] matching number
\ D = [^ 0-9] match non-numbers, same as [^ 0-9]
\ W [0-9A-Za-z _] matches letters and numbers and _
\ W match non-(letters, numbers, and _)

Character class: white space characters
Metacharacters/metacharacters
\ 0 matches null characters
\ B matches space characters
\ N match the linefeed
\ R matches the carriage return character
\ T matching tabs
\ S matches blank characters, spaces, tabs, and line breaks
\ S match non-blank characters

Character class: Anchor character

Metacharacters/metacharacters
^ Match the beginning of a row
$ Matching at the end of a row

Character class: repeated characters
Metacharacters/metacharacters
? For example (x ?) Match 0 or 1 x
* For example, (x *) matches 0 or any number of x
+ For example, (x +) matches at least one x
(Xyz) + match at least one (xyz)
{M, n} For example, x {m, n} n >=times> = m matches at least m and at most n x
{N} matches the previous item n times
{N,} matches the previous item n times or multiple times.

6. Common Regular Expression = (128) =

1. Check the zip code

Var pattern =/[1-9] [0-9] {5}/; // a total of six digits. the first digit cannot be 0var str = '000000'; alert (pattern. test (str ));

2. Check the compressed file package

Var pattern =/[\ w] + \. zip | rar | gz/; // \ w indicates that all numbers and letters are underlined var str = '123.zip ';//\. indicates matching ., next, select alert (pattern. test (str ));

3. Delete unnecessary Spaces

Var pattern =/\ s/g; // g must be global in order to all match var reg = new RegExp ('\ s +', 'G '); var str = '1970 111 222 '; var result = str. replace (pattern, ''); // matches spaces into spaces without alert (result );

4. Delete Spaces

Var pattern =/^ \ s +/; var str = 'Goo gl'; alert (str + "" + str. length); var result = str. replace (pattern, ''); alert (result +" "+ result. length); pattern =/\ s + $/; result = result. replace (pattern, ''); alert (result +" "+ result. length); pattern =/\ s +/g; result = result. replace (pattern, ''); alert (result +" "+ result. length); 5, simple email verification var pattern =/^ ([a-zA-Z0-9 _\. \-] +) @ ([a-zA-Z0-9 _\. \-] + )\. ([a-zA-Z] {2, 4}) $/; var str = 'yc4. com@gmail.com '; alert (pattern. test (str); var pattern =/^ ([\ w \. \-] +) @ ([\ w \. \-] + )\. ([\ w] {2, 4}) $/; var str = 'yc60. com@gmail.com '; alert (pattern. test (str ));

VII. String methods supporting regular expressions

Method Description
Search Retrieve the index of the first matching item that matches the regular expression.
Match Find the matching of one or more regular expressions.
Replace Replace the substring that matches the regular expression.
Split Splits a string into a string array.

<Script type = "text/javascript"> var s = "Abc123aBc"; alert (s. search (/abc/gi); alert (s. search (/abc/gi); // even if the global mode is set, each search will start from the beginning to find the exec () of the // match method and regular expression () the function of the method is the same, but the match will put all the matches in an array at a time, all return alert (s. match (/abc/gi); // Abc, aBc alert (s. replace (/[AB]/gi, "x"); // replace a or B with x var ss = s. split (/[0-9] +/gi); // cut with one or more numbers. Abc, aBc alert (ss); </script>

The above is the regular expression of the basic JS series introduced by xiaobian. I hope it will help you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!

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.