JS Regular Expression

Source: Internet
Author: User
Tags character classes string methods

js Regular Expression

1. Regular Expressions (English:Regular expression, often abbreviated in code as regex, RegExp, or re) uses a single string to describe and match a series of string search patterns that conform to a certain syntactic rule. The search mode can be used for text search and text substitution.

var expression=/pattern/flags;

where the Patternsection can be any simple or complex regular expression that can contain character classes, qualifiers, groupings, forward lookups, and reverse references. Each regular expression can have one or more flags (flags) that indicate the behavior of the regular expression.

3 Flags (Flags):

G: Global mode , which is applied to all strings, rather than stopping immediately when the first occurrence is found. I: Indicates case-insensitive mode , that is, the case of the pattern and string are ignored when the match is determined, and M: represents the multiline pattern , that is, when the end of a line of text is reached, the option to find out if there is a pattern match in the next row.

so, simply put, a regular expression is a pattern (pattern) with a combination of the 3 flags (flags) above.

2. Similar to regular expressions in other languages, all meta characters used in the pattern must be escaped.

The metacharacters in the regular expression include: ([{\ ^ $ |)? * +.]}

Example: Matches all ". At" in a string, not case-sensitive: var pattern=/\.at/gi; matches the first "[Bc]at", Case insensitive:var pattern=/\[bc\]at/i;

The above is a regular expression defined using the literal form. There is also a way to use the Regexg constructor . It receives two parameters: one is the string pattern to match, and the other is the optional flag string.

Such as:

var // Match First "bat" or "cat", case insensitive var pattern1=New RegExp ("[Bc]at", "I");  // equivalent to the literal amount

3, since the RegExp function pattern parameters are all strings, in some cases you want to double-escape the string. All metacharacters must be double-escaped, as are characters that have been escaped.

Cases

literal pattern                equivalent string /\[bc\]at/    "\\[bc\\]at"/\.at/"\\.at"/name\/age/"Name\\/age"/\d.\d{1,2}/"\\d.\\d{1,2}"/\w\\hello\\123/"\ \ W\\\\hello\\\\123 "  

4. Example method of Regexg constructor function

(1) the Exec () method is a regular expression method.

The exec () method is used to retrieve the matching of regular expressions in a string.

The function returns an array that holds the results of the match. If no match is found, the return value is null.

The following instances are used to search for letters in a string "E":

Example 1/e/.exec ("The Best things on life is free!");

(2) The test () method is a regular expression method.

The test () method is used to detect whether a string matches a pattern and returns true if the string contains matching text, otherwise false.

var patt =/e/;p att.test ("The best things on life is free!");

5. Using the String method

in JavaScript, regular expressions are typically used in two string methods: Search () and replace ().

The search () method retrieves the substring specified in the string, or retrieves a substring that matches the regular expression and returns the starting position of the substring.

The replace () method is used to replace other characters with some characters in a string, or to replace a substring that matches a regular expression.

Example 1:

searching with regular expressions "Runoob" string, and is case-insensitive:

var str = "Visit runoob!" ; var n = str.search (/runoob/i); // Output 6

Example 2:

use regular expressions and case-insensitive to Microsoft is replaced with Runoob:

var str = document.getElementById ("demo"). InnerHTML; var txt = str.replace (/microsoft/i, "Runoob"); // output is: Visit runoob!

6. Regular expression pattern

Square brackets are used to find characters in a range:

Expression description

[ABC] finds any character between square brackets. [^ABC] finds any characters that are not in square brackets. [0-9] Find any from 0 to 9the number. [A-Z] to find any characters from a to lowercase z. [A-Z] to find any characters from uppercase A to uppercase Z. [A-Z] to find any characters from uppercase A to lowercase z.  [ADGK] finds any character within a given collection. [^Adgk] finds any character outside the given set. (Red|blue|Green) to find any of the specified options. The metacharacters OFDM character (metacharacter) is a character that has a special meaning: a meta-character description^: Matches the starting position of the string $: match the end position of the string*: Match front face expression any number of times+: Match front face expression one or more times? : Matches the front face expression 0 or more times {n}:n is a nonnegative integer that matches the determined N times. For example: "O{2} "cannot match ' o ' in ' bod ', but can match ' food ' in ' 0 '' {n,}: match at least n times {n,m}: Minimum match n times, maximum match m x|y: Match x or Y[XYZ]: Character set. matches any one character. For example ' [ABC] ' matches ' a ' in ' plain ' [^XYZ]: Matches any characters that are not included. For example ' [^ABC] ' matches ' plin ' in ' plain '. Finds a single character, in addition to line breaks and line terminators. \w find word characters. \w Find non-word characters. \d find numbers. \d to find non-numeric characters. \s Find white space characters. \s find non-whitespace characters. \b matches the word boundary. \b Matches a non-word boundary. \0finds a NULL character. \ nto find newline characters. \f Find a page break. \ r to find the carriage return character. \ t to find a tab. \v Find vertical tabs. \xxx finds characters that are specified in octal number XXX. \XDD finds the characters specified in hexadecimal number DD. \uxxxx finds Unicode characters that are specified in hexadecimal number xxxx. quantifier quantifier description n +matches any string that contains at least one n. For example,/a+/matches "A" in "Candy", All "a" in "Caaaaaaandy". N *matches any string that contains 0 or more N. For example,/bo*/matches "B" in "a Ghost booooed" in "Boooo", "A bird warbled", but does not match "a goat grunted". N?matches any string that contains 0 or one n. For example,/e?le?/matches "El" in "Angel", "le" in "angle". N{x} matches a string containing a sequence of X N. For example,/a{2}/does not match "a" in "Candy," but matches the two "a" in "Caandy," and matches the first two "a" in "Caaandy.". N{x,}x is a positive integer. The preceding pattern n is matched at least X times consecutively. For example,/a{2,}/does not match "a" in "Candy", but matches all "a" in "Caandy" and "Caaaaaaandy.". N{x,y}x and Y are positive integers. The preceding pattern n appears consecutively at least X times, and matches at most Y times. For example,/a{1,3}/does not match "Cndy", matching "a" in "Candy," "Caandy," in two "a", matching the first three "a" in "Caaaaaaandy". Note that when "Caaaaaaandy" is matched, even if the original string has more "a", the match is also "AAA". N{x,} matches a string that contains at least X N of a sequence. n$ matches any string that ends with N. ^n matches any string that begins with N. ?=n matches any string immediately followed by the specified string n. ?!n matches any string that does not follow the specified string n immediately thereafter. 7, RegExp constructor property $_ the last string to match $&last occurrence $+The most recent time to match the capture group $ ' $_ string in $+before the text $*Boolean value that indicates whether all expressions use multiline mode. $' $_ text after $+ in string

Regular expression Form validation instances:

/*whether with decimals*/functionIsdecimal (strvalue) {varobjregexp=/^\d+\.\d+$/; returnobjregexp.test (strvalue); }  /*Check whether the Chinese name consists of*/functionIschina (str) {varreg=/^[\u4e00-\u9fa5]{2,4}$/;/*Defining validation Expressions*/returnReg.test (str);/*to verify*/}/*whether the checksum is made up of 8 digits*/functionIsstudentno (str) {varreg=/^[0-9]{8}$/;/*Defining validation Expressions*/returnReg.test (str);/*to verify*/}/*Verify Phone code format*/functionIstelcode (str) {varReg=/^ ((0\d{2,3}-\d{7,8}) | ( 1[3584]\D{9})) $/;returnreg.test (str);}/*verifying that the email address is legitimate*/functionIsemail (str) {varreg=/^ ([a-za-z0-9_-]) [email protected] ([a-za-z0-9_-]) + (\.[ A-za-z0-9_-]) +/;returnreg.test (str);} 

Attached: well-known regular expression solution

JS Regular Expression

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.