Introduction to Regular Expressions in JavaScript

Source: Internet
Author: User
Tags constructor modifier regular expression split

First, the method of defining regular expressions
There are two ways to define regular expressions: constructor definition and regular expression direct definition. For example: The code is as follows:

var reg1 = new RegExp ('d {5, 11}'); // Defined by the constructor var reg2 = / d {5, 12} /; // Defined regular expression by the direct literal character o: NUL character (U0000) t: tab (u0009) n: line feed (u000A) v: vertical tab (u000B) f: form feed (u000C) r: carriage return (u000D) xnn: by hexadecimal Latin characters specified by the number nn, for example, x0A is equivalent to n uxxxx: Unicode characters specified by the hexadecimal number xxxx, such as u0009 is equivalent to t cX: control character ^ X, for example, cJ is equivalent to the newline character n Regular expression anchor character ^: Matches the beginning of a string. In a multi-line search, matches the beginning of a line. $: Matches the end of a string. In multi-line retrievals, matches the end of a line. B: Matches the boundary of a word. In other words, it is the position between the characters w and W, or between the character w and the beginning or end of the string ([b] matches the backspace character) B: Matches the position of a non-word boundary (? = p): Wide-forward lookahead assertion, which requires that the following characters match p, but cannot include those characters that match p (?! P): Zero-width negative forward lookahead assertion, which requires that the next string does not match p regular expression Character class [...]: any character in square brackets [^ ...]: any character not in square brackets .: any character except newline and other Unicode line terminator w: any ASCII character Words that are equivalent to [a-zA-Z0-9] W: Any words that are not ASCII characters, equivalent to [^ a-zA-Z0-9] s: Any Unicode white space S: Any non-Unicode White space characters, note that w and S are different. D: Any ASCII number, equivalent to [0-9] D: Any character except ASCII number, equivalent to [^ 0-9] [b]: Backspace Direct (special case) Repeated character syntax for regular expressions {n, m}: Match the previous item at least n times, but not more than m times {n,}: Match the previous item n times or more {n}: Match the previous item n times ?: Match the previous item 0 times or 1 Times, that is, the previous item is optional, equivalent to {0, 1} +: matches the previous item 1 or more times, equivalent to {1,} *: matches the previous item 0 or more times Second, equivalent to {0,} regular expression selection, grouping, and quoting characters |: selection, matching the subexpression on the left or the subexpression on the right (...): combination, combining several items As a unit, this unit can be modified by symbols such as "*", "+", "?", And "|", and can remember the string matching this group for any subsequent use (?:… ): Only group, group the items into one unit, but do not remember the characters that match the reorganization n: match the character that the nth group matches for the first time, the group is a subexpression in parentheses (it is also possible Nested), the group index is the number of left parentheses from left to right, grouping in the form "(?:" Does not encode the regular expression modifier i: perform a case-insensitive match g: perform a global match, in short In other words, find all matches instead of looking for Stop m after the first one: multi-line matching pattern, ^ matches the beginning of a line and the beginning of a string, $ matches the end of a line and the end of a string. The String method search () for pattern matching: its argument is a Regular expression, returns the starting position of the first matching substring, or -1 if there is no matching substring. If the argument of search () is not a regular expression, it will first be converted to a regular expression through the RegExp constructor. Search () does not support global retrieval because it ignores the modifier g. For example: The code is as follows: var s = "JavaScript" .search (/ script / i); // s = 4 replace (): It is used to perform retrieval and replacement. Takes two parameters, the first is a regular expression and the second is the string to be replaced. The regular expression, if the modifier g is set, is replaced globally, otherwise only the first substring that matches is replaced. If the first parameter is not a regular expression, the string is searched directly instead of being converted to a regular expression. For example: The code is as follows: var s = "JavaScript" .replace (/ java / gi, "Script"); // s = Script Script match (): Its parameter is a regular expression. If it is not, it is converted by RegExp. What is returned is an array of matching results. If the modifier g is set, global matching is performed. For example: The code is as follows: var d = '55 ff 33 hh 77 tt'.match (/ d + / g); // d = ["55", "33", "77"] split (): This method is used to Split the string that calls it into an array of substrings. The separator used is the argument of split (). Its argument can also be a regular expression. For example: The code is as follows: var d = '123,31,453,645'.split (', '); // d = ["123", "31", "453", "645"] var d = '21, 123, 44, 64, 67, 3'.split (/ s *, s * /); // d = ["21", "123", "44", "64", "67", "3"]

RegExp objects

  Each RegExp object has 5 attributes. The attribute source is a read-only string containing the text of the regular expression. The global attribute is a read-only Boolean value that indicates whether this regular expression has the modifier g. The attribute ignoreCase is a read-only Boolean value that indicates whether this regular expression has the modifier i. The attribute multiline is a read-only Boolean value that indicates whether this regular expression has the modifier m. The property lastIndex is a readable and writable integer. If the matching pattern has the g modifier, this property stores the start position of the next retrieval in the entire string. The RegExp object has two methods. The parameter of exec () is a string, and its function is similar to match (). The exec () method executes a regular expression on a specified string, that is, performs a matching search in a string. If no match is found, null is returned, and an array is found. The first element of the array contains the string that matches the regular expression, and the remaining elements are the subexpressions in parentheses. The matched substring, regardless of whether the regular expression has the modifier g, will return the same array. When the regular expression object calling exec () has the modifier g, it will set the lastIndex property of the current regular expression object to the character position next to the matching substring. When the same regular expression calls exec () for the second time, it will start to retrieve from the string indicated by the lastIndex property. If exec () does not find any matching results, it will reset lastIndex to 0. For example: The code is as follows: var p = / Java / g; var text = "JavaScript is more fun than Java!" Var r; while ((r = p.exec (text))! = Null) {console.log (r , 'lastIndex:' + p.lastIndex);} Another method is test (). Its parameter is a string. Use test () to check a string. If it contains a match result of the regular expression, It returns true otherwise it returns false. For example: The code is as follows: var p = / java / i; p.test ('javascript'); // true

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.