Regular Expression common usage summary, regular expression Summary

Source: Internet
Author: User

Regular Expression common usage summary, regular expression Summary

Before reading the text, let's introduce it to you.Basic concepts of Regular Expressions:

Regular Expressions, also known as regular and regular expressions. (English: Regular Expression, often abbreviated as regex, regexp or RE in code), a concept of computer science. Regular Expressions use a single string to describe and match a series of syntaxes. In many text editors, regular expressions are usually used to retrieve and replace texts that match a certain pattern.

Regular Expression, like me, I learned it several times, but it was still very difficult. When I learned it, I understood it and forgot it. Well, actually, it's not enough to practice. The so-called "Learn from the story" can be a teacher. Let me review this proud regular expression today.

Why is there a regular expression? In fact, it is because of the Computer stupid (this is not what I said), such as 123456@qq.com, we look at the mailbox, but the computer does not know Ah, so we need to use some computer know the language, to develop the rules, tell it to comply with this rule is a mailbox, so that the computer can help us find the corresponding thing. Therefore, regular expressions are used to set rules to perform the operations we need, such as logon verification and searching for specified items. If you say too much, it is unnecessary. Let's look at the subject directly.

Define Regular Expressions:

1 var re = new RegExp ("a"); // RegExp object. Parameters are the rules we want to develop. This method must be used in one case. 2 var re =/a/; // It is recommended to use a simplified method with better performance. Do not leave it blank or think it is a comment,

Common Regular Expressions

1 test (): Find the regular content in the string. If true is returned, false is returned.

Usage: Regular. test (string)

Example: Determine if it is a number

Var str = '100'; var re =/\ D/; // \ D indicates non-numeric if (re. test (str) {// returns true, which indicates that a non-number is found in the string. Alert ('all digits ');} else {alert ('all digits ');}

Regular expressions have many symbols that indicate different meanings. They are used to define different rules, such as the above \ D and the following:

\ S: Space
\ S: non-space
\ D: Number
\ D: Non-numeric
\ W: character (letter, number, underline _)
\ W: Non-character example: whether there are non-numeric characters

(The following describes some frequently-used Characters Based on the examples, and then summarizes them .)

2 search (): search for the regular content in the string, and return the position where it appears (starting from 0, if the match is not just a letter, returns the position of the first letter. If the search fails, the value-1 is returned.

Usage: String. search (regular)

Search for the compound regular content in the string. Case-insensitive: I -- ignore (in regular expressions, It is case-sensitive by default. If it is case-insensitive, add the id I at the end of the regular expression)

Example: Find the letter B in the string, which is case-insensitive

Var str = 'abcdef'; var re =/B/I; // var re = new RegExp ('B', 'I'); you can also write alert (str. search (re); // 1

3. match () searches for the content of the compound rule in the string. if the search is successful, the returned content is in the array format. If the search fails, null is returned.

Usage: String. match (regular)

Quantifiers: + at least one uncertain match (matching means searching)

Global match: g -- global (default in the regular expression, the search will end if the content of the compound rule is found)

Example: Find All numbers in the specified format. For example, find 123,54, 33,879.

var str = 'haj123sdk54hask33dkhalsd879';

Var re =/\ d +/g; // match at least one number at a time. If the global match is not a global match, it stops when the number 123 is found. Only 123 is displayed. With global matching, the system searches for matching rules from the beginning to the end. If there is no plus sign, the matching result is 1, 3, 5, 4, 3, 3,879, which is not what we want. With the plus sign, each matching number is at least one.

alert( str.match(re) ); // [123,54,33,879]

4 replace (): Find a regular string and replace it with the corresponding string. Return the replaced content.

Usage: String. replace (Regular Expression, New String/callback function) (in the callback function, the first parameter indicates the characters that match successfully each time)

|: Or.

Example: sensitive word filtering, for example, I Love Tiananmen, Beijing, and the sun rises on Tiananmen. ------ I love * and. That is, Beijing and Tiananmen are changed to,

In the beginning, we may think of the following method:

Var str = "I Love Tiananmen, Beijing. The sun rises on Tiananmen. "; Var re =/Beijing | Tiananmen Square/g; // find the global match var str2 = str in Beijing or Tiananmen Square. replace (re, '*'); alert (str2) // I love **, * Rising Sun // This only turns what is found into *, it cannot contain a few words *.

To implement several words corresponding to several characters *, we can use the callback function:

Var str = "I Love Tiananmen, Beijing. The sun rises on Tiananmen. "; Var re =/Beijing | Tiananmen Square/g; // find the global match var str2 = str in Beijing or Tiananmen Square. replace (re, function (str) {alert (str); // used for testing: the first parameter of the function represents the regular character that is found each time, so the first str refers to the second str in Beijing, the third str in Tiananmen, And the var result = ''in Tiananmen Square; for (var I = 0; I <str. length; I ++) {result + = '*';} return result; // a few words are returned *}); alert (str2) // I love *, * the sun rises

// The entire process is to find Beijing, replace it with two characters *, replace Tiananmen with three characters *, and replace Tiananmen with three characters *.

Replace is a very useful method and is often used.

Characters in the Regular Expression

(): Parentheses, called group characters. It is equivalent to brackets in mathematics. As follows:

Var str = '1970-6-7 '; var re1 =/\ d-+/g; // global matching number, horizontal bar, number of horizontal bars at least 1, matching result: 3-6-var re1 =/(\ d-) +/g; // global matching number, horizontal bar, number and overall number of horizontal bars must be at least 1-6-var re2 =/(\ d +) (-)/g; // global match must contain at least one number and match with one horizontal bar match result: 2013-6-

At the same time, every item with parentheses in the regular expression is called the subitem of the regular expression. Subitem is very useful in some cases, for example, let's look at a chestnut.

Example: Change 2013-6-7 to 2013.6.7

Var str = '1970-6-7 '; var re =/(\ d +) (-)/g; str = str. replace (re, function ($0, $1, $2) {// replace () If there is a subitem, // The first parameter: $0 (the overall result 2013-6-after successful match), // The second parameter: $1 (the first group after successful match, which indicates \ d 2013, 6) // The third parameter: $1 (the second group that matches successfully, which indicates---) return $1 + '. '; // return 2013 respectively. 6 .}); alert (str); // 2013.6.7 // the entire process is to use the subitem to replace 2013-6-with 2013 respectively. 6. finally, 2013.6.7 is displayed.

The match method also returns its own subitem, as shown below:

Var str = 'abc'; var re =/(a) (B) (c)/; alert (str. match (re); // [abc, a, B, c)

[]: Indicates any one of a set. For example, [abc] indicates that a character matches any one of a B c, or a range, [0-9] The range must be small to large.

[^ A] indicates a single character. ^ if it is written in [], it indicates exclusion.

Example: matching HTML tags, such as <div class = "B"> hahahah </div>, to find the tag <div class = "B"> </div>

Var re =/<[^>] +>/g; // match at least one content in the left brace that is not in the right brace (because there are attributes and other things in the tag ), then match the right parenthesis
Var re =/<[\ w \ W] +>/g; // matches at least one or more characters in the left parentheses, then match the right parenthesis // In fact, it is to find the left parenthesis, and there can be at least one content in the middle, until the right parenthesis is found, it indicates a label.

Escape characters

\ S: Space
\ S: non-space
\ D: Number
\ D: Non-numeric
\ W: character (letter, number, underline _)
\ W: Non-Character
. (Point) -- any character
\.: Real point
\ B: independent part (START, end, space)
\ B: non-independent part

Let's look at the last two chestnuts:

Var str = 'onetwo '; var str2 = "one two"; var re =/one \ B/; // e must be followed by an independent start or space, or end alert (re. test (str); // falsealert (re. test (str2); // true

Example: Write a function that uses the class name to get the node:

We may have seen such a function before:

Function getByClass (parent, classname) {if (parent. getElementsByClassName) {return parent. getElementsByClassName (classname);} else {var results = new Array (); // The var elems = parent. getElementsByTagName ("*"); for (var I = 0; I <elems. length; I ++) {if (elems [I]. className = classname) {results. push (elems [I]) ;}} return results ;}}

This is actually a problem. For example, if a tag contains two classes or a class with the same name, for example, <div class = "box1 box1">, <div class = "box1 box2> it cannot be obtained. We can use regular expressions to solve this problem.

Function getByClass (parent, classname) {if (parent. getElementsByClassName) {return parent. getElementsByClassName (classname);} else {var arr = []; var aEle = parent. getElementsByTagName ('*'); // var re =/\ bclassname \ B/; // cannot be written in this way. When a regular expression requires a parameter, it must be written in the full name, in short, classname is used as a string for matching. Var re = new RegExp ('\ B' + classname + '\ B'); // when matching, classname must start with a space or followed by a space. By default, a successful match is stopped, so even if there are duplicates, it will not be matched again. // It should be noted that when the full name is used to declare a regular expression, the parameters are of the string type. Therefore, we need to ensure that these special characters can be output in the string. \ Bitself is a special character and cannot be output in the string. Therefore, you must add a backslash to escape the character. For (var I = 0; I <aEle. length; I ++) {if (re. test (aEle [I]. className) {arr. push (aEle [I]) ;}} return arr ;}}

\ A indicates a repeated subitem, for example:

\ 1 the first sub-item that repeats

\ 2 duplicate second sub-item

/(A) (B) (c) \ 1/----- match abca
/(A) (B) (c) \ 2/------ match abcb

Example (frequently asked in Interview Questions): Find the maximum number of characters for repeated items

Split (): The method in the string to convert the string into an array.

Sort (): sorting method in the array, sorted by the ACALL code.

Join (): The method in the array to convert the array to a string.

Var str = 'assssjdssskssalsssdkjsssds'; var arr = str. split (''); // converts a string to an array str = arr. sort (). join (''); // sort the strings first, so that the same characters are put together and then converted to a string // alert (str ); // aaddjjkklsssssssssssssssssvar value = ''; var index = 0; var re =/(\ w) \ 1 +/g; // The character must be repeated, repeat at least once. Str. replace (re, function ($0, $1) {// alert ($0); indicates the result of each successful match: aa dd jj kk l sssssssssssssssssss // alert ($1); indicates the first sub-item that is successfully matched, that is, \ w: a d j k l S if (index <$0. length) {// if the index value is smaller than the length of $0, perform the following operation index = $0. length; // so that the index is always saved in the maximum length value = $1; // The value stores the most frequently-seen character }}); alert ('maximum character: '+ value +', repeated times: '+ index); // s 17

Quantifiers: the number of occurrences.

{N, m}: appears at least n times, at most m times

{N ,}: at least n times

*: Any time is equivalent to {0 ,}

? : Zero or one time is equivalent to {0, 1}

+: One or any time is equivalent to {1 ,}

{N}: Exactly n times

Example: Determine if it is a QQ number

// ^: Place it at the beginning of the regular expression, which indicates the start point. Note that/[^ a]/and/^ [a]/are different. The former indicates exclusion, the latter represents the first place.

// $: The last position of the regular expression, which indicates the end.

// First, consider the QQ number rules

1. the first digit cannot be 0.

2 must be 5-12 digits

Var aInput = document. getElementsByTagName ('input'); var re =/^ [1-9] \ d {4, 11} $/; // 123456abc to prevent such a situation, therefore, the last // first digit must be 0-9, followed by 4-11 digits. AInput [1]. onclick = function () {if (re. test (aInput [0]. value) {alert ('qq No. ');} else {alert (' not QQ No ');}};

Example: Remove leading and trailing spaces (frequently used in interview questions)

Var str = 'hello'; alert ('+ trim (str) +'); // brackets are added to indicate the difference. (Hello) function trim (str) {var re =/^ \ s + | \ s + $/g; // | represents or \ s represents space + at least one leading space or at least one trailing space and globally matches return str. replace (re, ''); // replace spaces with null}

Common Form Verification

Match Chinese characters: [\ u4e00-\ u9fa5] // range of Chinese ACALL Codes

Space at the end of the first line of the line: ^ \ s * | \ s * $ // any space at the beginning or at the end of the line (it can be expressed as no space)

Email: ^ \ w + @ [a-z0-9] + (\. [a-z] +) {} $
// Start with at least one character (\ w letters, numbers or underscores), then match @, then any letter or number ,\. represents the real point ,. followed by at least one character (a-z. com. Because some mailboxes are like .cn.net. Xxxx.@qq.com

Xxxx.@163.com xxxx.@16.cn.net)

URL: [a-zA-z] +: // [^ \ s] * http ://......

// Match any case-insensitive letters followed by //, followed by any non-space characters

Zip code: [1-9] \ d {5} // The Starting number cannot be 0, followed by 5 digits

ID card: [1-9] \ d {14} | [1-9] \ d {17} | [1-9] \ d {16} x

To facilitate and avoid conflicts, we can create our own space in json format, as shown below:

/*var re = {email : /^\w+@[a-z0-9]+(\.[a-z]+){1,3}$/,number : /\d+/};re.email*/

The above is a summary of common usage of Regular Expressions introduced by xiaobian. 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.