JS Basic series of regular expressions _ regular expressions

Source: Internet
Author: User
Tags array length character classes modifier modifiers regular expression string methods zip

Regular expression is a very good thing, today here is just a simple to contact JS people, if there is a controversial place to welcome everyone to leave a message!

1.1 What is a regular expression

A regular expression (regular expression) is an object that describes a character pattern, and the RegExp class of ECMAScript represents a regular expression, while string and RegExp define functions that use regular expressions for strong pattern matching and text retrieval and substitution.

Regular expressions are used to match string patterns and retrieve replacements, and are powerful tools for performing pattern matching on strings.

1.2 The role of regular expressions

Regular expressions are used primarily to validate the input data of a client.

After the user fills out the table click button, the form is sent to the server, which is usually processed further with a server script such as PHP, ASP.net, and JSP on the server side. Because of client authentication, you can save a lot of server-side system resources and provide a better user experience.

Second, the creation of regular expression = = (123) = =

To use regular expressions, you must first create a regular expression object, and there are 2 ways to create the object:

2.1 Mode 1: Using the keyword new to create

var Patt = new RegExp (pattern,modifiers);

Parameter 1: The pattern of the regular expression. String form

Parameter 2: pattern modifier. Used to specify global matches, case-sensitive matches, and multiline matching

<script type= "Text/javascript" >
   /* Creates a regular expression
   parameter 1: The pattern is: girl, meaning that you can match a string
   such as "Girl" Parameter 2: pattern modifier: GI G represents a global match I representative case-insensitive
 /var pa = new RegExp ("Girl", "GI");
  The string in the test parameter "Hello my Girl" matches the matching pattern.
  var isexist = pa.test ("Hello My Girl");//In this case, it is a match, this string contains girl, so return true
  alert (isexist);//true
</ Script>

2.2 Mode 2: Use regular expression Direct quantity

var pa =/pattern/modifiers;

Two/middle mode representing regular expression, last/followed by pattern modifier

For example: The above example can write var pa =/girl/gi;

Note: Both the pattern and pattern modifiers can be added double or single quotes at this time

<script type= "Text/javascript" >
 var pa =/girl/gi;
 Alert (Pa.test ("My Girl"); True
</script>

Third, regular expression pattern modifier = = (126) = =

JavaScript has 3 pattern modifiers: G i u

    1. G: Represents the Global. It means that a string will be matched multiple times. If you do not write G then only match once, once the match is successful, will not match again
    2. I: Indicates that case is ignored. It means that the match is not case-sensitive.
    3. U: Indicates that multiple rows can be matched.

Four, regular expression method detailed explanation = = (127) = =

Regular expression methods that are often used have two test () and exec ()

4.1 Test () method

Test (String)

    • Parameters: String to match
    • Return value: Match successfully returns true, Failure returns false

This is handy when you want to know if the target string matches a pattern, but you don't need to know its textual content. Therefore, the test () method is often used in an if statement.

<script type= "Text/javascript" >
 var pa =/girl/gi;
 if (Pa.test ("Awesome My Girl")) {
  alert ("This girl is good with You");
 } else {
  alert ("You are destined to have no girl to match");
 }
</script>

4.2 Exec () method

EXEC (String): This method is designed specifically for capturing groups

    • Parameters: String to match
    • Return value: Returns an array. Return NULL if not matched
    • A description of the array of returned values:
    • It is indeed an instance of array.
    • But this array has two additional attributes: Index and input
    • Index: Indicates that a matching string is indexed in the source string
    • Input: Represents a matching source string.
    • The first item in the array is a string that matches the entire pattern, and the other items are strings that match the capturing group in the pattern
    • If no group is captured, only the first item in the array is available. About capturing the group concept later
<script type= "Text/javascript" >
 var pa =/girl/gi;
 var teststr = "Mygirl, Yourgirl, hisgirl";
 var girls = pa.exec (TESTSTR); Capture
 Alert (girls.length + ":" + (Girls instanceof Array)); The regular expression does not capture the group, so the array length is 1
 alert (girls[0]);//The first capture is Girl
  //Because we are using a global match, so this time the match starts with the last post position to match
 alert ( Pa.exec (TESTSTR) [0]);  Girl
 alert (pa.exec (TESTSTR));//Girl
 alert (pa.exec (TESTSTR));//Continue back without a matching string, so return null
  //return NULL, If you continue to match, you return to the beginning of the string and the rewrite starts to match.
 alert (pa.exec (TESTSTR));//Girl
  //... Open a new round of matching
</script>

So if we want to find all the matching strings, we can use loops, and the end condition is that the result is null.

<script type= "Text/javascript" >
 var pa =/girl/gi;
 var teststr = "Mygirl, Yourgirl, hisgirl";
 var girls;
 while (girls = Pa.exec (teststr)) {//if equal to NULL, automatically turns to false and ends.
  alert (girls);
 }
</script>

Group. The task is a set of () in a regular expression. Groups can be nested.

<script type= "Text/javascript" >
  //() content is the 1th group (Girl), in fact, we can see the complete whole expression of the No. 0 Group Girl (Girl)
  // A subscript that corresponds to an array of matched results in the future. 
 var pa =/girl (girl)/gi; 
 var test = "Girlgirl abdfjla girlgirl fal Girl";
 var girls;
 while (girls = pa.exec (test)) {
  //match, the No. 0 element of the array corresponds to the result of this No. 0 group, the 1th element corresponds to the match result for the 1th group for
  (var i = 0; i < Girls.length; i++) {
   console.log (girls[i]);
  }
  Console.log ("-------------");
 }
</script>
//Final run results:
girlgirl
Girl
-------------
girlgirl
Girl
------- -----

Rules of regular expression = = (124) = =

An expression rule

A regular expression meta character is a character that contains special meaning. They have some special features that can control the matching pattern of

Way. The metacharacters after the backslash will lose its special meaning.

Character classes: Single characters and numbers

[0-9a-za-z]
metacharacters/meta symbol matching
. Match any character except the line feed
[a-z0-9] matches any character in the character set in parentheses
[^a-z0-9] matches characters in any character set that is not in parentheses
\d ==[0-9] matching numbers
\d ==[^0-9] matches non-numeric, same as [^0-9]
\w [0-9a-za-z_] matches letters and numbers and _
\w matching non (letters and numbers and _)

Character classes: whitespace characters
metacharacters/meta symbol matching
To match a null character
\b Matching whitespace characters
\ n Match line break
\ r matching Carriage return characters
\ t matches tabs
\s matches white space characters, spaces, tabs, and line breaks
\s matching Non-white-space characters

Character classes: Anchor characters

metacharacters/meta symbol matching
^ Line header Matching
$ line End Match

Character classes: repeating characters
metacharacters/meta symbol matching
? For example (x?) matches 0 or 1 x
* For example (x*) match 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>= number >=m match least m, max N x
{n} matches previous n times
{n,} matches n times before, or multiple

Six, commonly used regular means = = (128) = =

1. Check ZIP code

var pattern =/[1-9][0-9]{5}/; A total of 6 digits, the first digit cannot be 0
var str = ' 224000 ';
Alert (Pattern.test (str));

2, check the file compression package

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

3, remove extra space

var pattern =/\s/g; G must be global to match all the
var reg=new RegExp (' \\s+ ', ' G ');
var str = ' 222 333 ';
var result = Str.replace (pattern, '); Match the space to no space
alert (result);

4, delete space

var pattern =/^\s+/; 
var str = ' goo gle ';
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 = ' yc60.com@gmail.com ';
Alert (Pattern.test (str));
var pattern =/^ ([\w\.\-]+) @ ([\w\.\-]+) \. ([\w]{2,4}) $/;
var str = ' yc60.com@gmail.com ';
Alert (Pattern.test (str));

Seven, string methods that support regular expressions

Method Description
Search Retrieves the index of the first occurrence that matches the regular expression.
Match Finds a match for one or more regular expressions.
Replace Replaces the substring that matches the regular expression.
Split Splits the string into an array of strings.

<script type= "Text/javascript" >
 var s = "Abc123abc";
 Alert (S.search (/ABC/GI)); 
 Alert (S.search (/ABC/GI)); Even if you set the global mode, each search is also the same as the Exec () method of the regular expression from the start backwards,
 but match puts all the matches in one array at a time, and returns all
 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 1 or more digits. ABC,ABC
 Alert (ss);
</script>

The above is a small set to introduce the JS Basic series of the regular expression, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.