Summary of JavaScript Regular expressions

Source: Internet
Author: User



Why use regular expressions

Regular Expressions use a text template consisting of ordinary and special characters to complete the validation, search, and substitution of strings. It's like this in JavaScript.
    1. /^1\d{10}$/
Copy CodeThe simple regex above is used to match the phone number. As for the meaning of the regular expression, it is summed up by a sentence in the "proficient regular expression".  ? " If you list the great inventions in the field of computer software, I believe there will never be more than 20 items in this list, which of course should include packet switching networks, WEB,LISP, hashing Algorithms, UNIX, compilation techniques, relational models, object-oriented, XML, these famous guys, And the regular expression should never be missed out.  for many practical tasks, regular expressions are a panacea, which can improve development efficiency and program quality. "



Generation of regular expressions

There are two ways to generate regular expressions in JavaScript
  • Call the constructor of the RegExp object
    1. var reg = new RegExp (' ^[a-z]+[0-9][align=left][font= Microsoft Black][size=3][color= #000000] [ Backcolor=white] Where the first parameter is a matching pattern, the second parameter is an optional parameter (g, I, M), which is used to specify global matching, case-sensitive matching, and multiline matching. This approach is compiled during the regular expression runtime (Runtime Compilation). If you know that the regular expression pattern will change, or you do not know what patterns you have in advance, but you get them from another source, such as user input, you can use constructors for these situations. [/backcolor] [/color] [/size] [/font] [/align]
    2. [*][align=left][font= Microsoft Jas-][size=3][color= #000000][backcolor=white] uses regular expression literals to enclose the matching pattern in two slashes [/backcolor][/ Color][/size][/font][/align][code]var reg =/^[a-z]+[0-9]$/gi
    copy code < Span style= "Font-size:medium" >


The composition of regular expressions

The literal template for regular expressions consists of a number of different types of characters, including:metacharacters, escape characters, qualifiers, character groups, or structures, grouping of parenthesesMeta character
Character Meaning
. Match all characters except line break (n)
W Match letters, numbers, or kanji
W Matches characters other than letters, numbers, kanji
D Match numbers
D Match a character other than a number
S matches any whitespace character (f, N, R, T, v)
S Match any character other than a white space symbol
B Match the beginning or end of a word
B Match the non-start or end of a word
^ Match beginning
$ Match end of Line
 Escape Character* + ? | { [ ( ) ] }^ $ . # and whitespace these characters all need to be escaped. For example, we want to match {.
    1. \{
Copy Code Qualifier
Character Meaning
* Match 0 times to multiple times
+ Match once to multiple times
Match 0 or one time
{2,} Match at least two times
{10} Matched 10 times
{{2, 8}} Match at least two times to match eight times
 character Group []The Bracket character group is used to match one of the characters in parentheses
    1. ' Fasfagxfasdfyfasfz '. Split (/[xyz]/)//["Fasfag", "Fasdf", "fasf", "" "
Copy CodeThere is also a group of excluded characters
    1. ' Xaxbycz '. Split (/[^xyz]/)//["x", "X", "Y", "Z"]
Copy Codeor structure |such as c|d matches or D
    1. /c|d/.test (' AF ')//False
    2. /c|d/.test (' ad ')//True
Copy Code grouping parentheses(CD) {1,} can match CDCD. And so on, where CD is a grouping.
    1. /(CD) {1,}$/.test (' CDCD ')//true
Copy Code



Greedy mode and non-greedy mode

by default, all qualifiers are greedy mode, which means to capture as many characters as possible. Instead of adding "?" to the qualifier, the non-greedy mode means to capture as few characters as possible.
    1. ' CCCCCCD '. Match (/c+/)//["CCCCC"], greedy mode, captures all
    2. ' CCCCCCD '. Match (/c+? /)//["C"], non-greedy mode, capturing only the first
Copy Code



Capturing groupings

in practical applications we are likely to need to obtain a matching string, for example, we want the string "Miles blue sky floating white clouds" to replace "Miles blue sky no white clouds"
    1. "Wanli Blue sky floating in a white cloud." Replace (/(miles blue sky) floating white clouds/, ' not a white cloud '
Copy Codecapturing a group creates a reverse reference, which can be referenced by $+number or "backslash" +number notation.  Note:Backslash +number This reference can be used in regular expressions and can be used to match the same substring in different locations, for example:
    1. ' www.bai.bai.com '. Replace (/([a-z]+) \.\1/, ' $ ')//www.bai.com
Copy Code

non-capturing groupingnon-capturing groupings, usually consisting of a pair of parentheses with a "?:" plus a subexpression, and a non-capturing grouping does not create a reverse reference, as if there were no parentheses. Capturing groups and non-capturing groupings are no different in terms of search efficiency, and no one is faster than the other.
    1. /^(?:\ d+)/
Copy Code



Methods of regular expressions

Testretrieves the specified substring in a string and returns a Boolean value
    1. /^\d[a-za-z]{3}$/.test (' 1AAC ')//True
Copy Code

execreturns an array in which the first entry in the array is the first match
    1. /^\d[a-za-z]{3}$/.exec (' 1AAC ')//["1AAC"]
Copy Code



String can use a regular expression method

Searchreturns the starting position of a substring
    1. ' A12b2334c34 '. Search (/\d{4}/)//4
Copy CodeMatchreturns the substring that is matched to
    1. ' A12b2334c34 '. Match (/\d{4}/)//["2334"]
Copy CodeReplacereplace the substring that matches the string
    1. ' A12b2334c34 '. Replace (/\d{4}/, ' CCCC ')//"A12BCCCCC34"
Copy CodeSplitto split a string into an array
    1. ' A12b2334c34 '. Split (/\d{4}/)//["a12b", "C34"]
Copy Code



Assertion

forward assertion (? =exp)represents a position in a string that follows a sequence of characters immediately after that position to match the exp
    1. /f (? =234)/.test (' 123ABCF234ACD ')//true
Copy Codenegative antecedent assertion (?! EXP)represents a position in a string that does not match the sequence of characters immediately after that position. Exp
    1. /f (?! 234)/.test (' 123ABCF234ACD ')//false
Copy Code



Common Regular Expressions

Email Address:
    1. ^\w+ ([-+.] \w+) *@\w+ ([-.] \w+) *\.\w+ ([-.] \w+) *$
Copy CodeURL Validation
    1. [A-za-z]+://[^\s]* or ^http://([\w-]+\.) +[\w-]+ (/[\w-./?%&=]*)? $
Copy CodePassword Verification
    1. (?! ^[0-9]+$) (?! ^[a-z]+$) (?! ^[^a-z0-9]+$) ^[^\s\u4e00-\u9fa5]{6,16}$
Copy CodePostcode Verification
    1. [1-9]d{5} (?! D
Copy CodeMobile phone number verification
    1. ^1\d{10}$
Copy CodeChinese Character Verification
    1. ^[\u4e00-\u9fa5]{0,}$
Copy Code

View Original: JavaScript Regular expression Summary

Summary of JavaScript Regular expressions

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.