Regular expressions in JavaScript

Source: Internet
Author: User

The following is a note from the section on pattern matching for regular expressions in the JavaScript authoritative guide (sixth edition).

Defined

There are two ways to define regular expressions in javascript:

    1. var pattern =/s$/; or
    2. var pattern = new RegExp (' s $ ');
Direct Volume characters
    1. All letters and numbers are matched by literal means
    2. Non-alphabetic characters match, using backslashes \. As the following table
character Match
alphabetic and numeric characters Their own
\o Nul character (\u0000)
\ t tab (\u0009)
\ n Line Break (\u000a)
\v Vertical tab (\U000B)
\f Page Break (\u000c)
\ r Carriage return character (\u000d)
\xnn Latin characters specified by the hexadecimal number NN, for example \x0a equivalent to \ n
\uxxxx Unicode characters specified by the hexadecimal number xxxx, such as \u0009 equivalent to \ t
\cx Control character ^x, for example, \CJ equivalent to line break \ n

Character class

The character class is formed by placing direct volume characters in square brackets alone.

For example [ABC] matches a or B or C

You can use ^ to indicate negation
You can use hyphens to represent ranges [a-za-z0-9]

Some characters are commonly used, so in a concise way, the following table shows:

character Match
[...] Any character in square brackets
[^ ...] Any character that is not in square brackets
. Any character except newline characters and other Unicode line terminators
\w A word of any ASCII character, equivalent to [a-za-z0-9]
\w Any word that is not an ASCII character, equivalent to [^a-za-z0-9]
\s Any Unicode whitespace character
\s Any non-Unicode whitespace characters, note that \w and \s are different
\d Any ASCII number, equivalent to [0-9]
\d Any character other than an ASCII number, equivalent to [^0-9]
[\b] Backspace Direct Volume (special case)

Note: \b has a special meaning, see below, to indicate the direct amount of backspace, the brackets are required.[\b]

Repeat

The syntax is shown in the following table:

character meaning
{N,m} Matches the previous item at least n times, but not more than m times
{N,} Match the previous item at least n or more times
N Matches the previous n times
? Matches the previous item 0 or 1 times, equivalent to {0,1}, which means that the previous item is optional
+ Matches the previous item 1 or more times, equivalent to {1,}
* Matches the previous item 0 or more times, equivalent to {0,}

Non-greedy repetition
The matching repeating characters listed in the table above are as many matches as possible and allow subsequent regular expressions to continue to match, so we call it greedy .    To make a non-greedy match, just follow a question mark with a matching character ? You can: ?? 、 +? And so on.

Select, group, and reference
    • Characters | are used to split the selected characters, similar to or. Note: The attempt to match the selected items is from left to right until a match is found. If the selection on the left matches, the back match is ignored, even if there is a better match .
    • Grouping references using parentheses()

Three functions:

    • Combine individual items into expressions so that you can use the | * +? To process items within a cell, as you would with a single unit.

    • Defines a sub-pattern in the full pattern. When a regular expression succeeds in matching the target string, the part that matches the sub-pattern of parentheses can be drawn from the target strings. (The book is followed by a detailed explanation)

    • Allows you to reference the preceding subexpression at the back of the same regular expression. Implemented by \ adding one or more digits to the character, the number represents the position of the subexpression in the regular expression. For example: /([Jj]ava ([Ss]cript)?) \sis\s (fun\w*)/In ([ss]cript) can be used to refer to \2.

Note: A reference to a regular expression word expression is not a reference to a subexpression pattern, but rather a reference to the text that matches that pattern, so that the reference can be used to implement a constraint where the individual parts of a string contain exactly the same characters, for example:
/[' "][^ '"]*[' "]/match 0 or more non-quoted characters between single quotes or double quotes, but he cannot have the quotes on both ends of the function match, can be changed to such /(['"]) [^ ' "]*\1/, but if so write /(['"]) [^\1]* \1/is wrong, the regular expression does not allow single quotes inside the double quotation marks, and vice versa.
Retrieval and substitution strongly depend on this attribute.

specify a matching location

The characters that match the position are also known as anchors of regular expressions. As the following table:

character meaning
^ Matches the beginning of the string, and then in multiple rows of the search, matches the beginning of a line
$ Matches the end of a string, in a multi-row search, matches the end of a line
\b Matches the boundary of a word, in short, the position between \w and \w, or the position between the character \w and the beginning or end of a string
\b Match the position of a non-word boundary
(? =p) 0 wide forward antecedent assertion, which requires that the next character be matched to p, but does not include those characters that match P
(?! P 0 wide Negative lookahead assertion, requires that the next character does not match p

A few examples:

Match word JavaScript, using /^javascript$/
To match the Java word itself, you need to use /\bjava\b/
/[jj]ava ([ss]cript)? (? =\:)/Can match javascript:the definitive Guid, cannot match Java in Java is.
/java (?! Script (a-z\w*)/can match JavaBeans but does not match JavaScript.

modifier
character meaning
I Case insensitive
G Global match, in short, find all matches instead of finding one to stop
M Multiline match, ^ matches the beginning of a line and the beginning of the string, the end of the matching line and the end of the string

string method for pattern matchingSearch () method

The parameter is a regular expression that returns the starting position of the first string to match, and returns 1 if no matching string is found. For example: ‘JavaScript‘.search(/script/i) return 4.

Also, the search method does not support global search because it ignores the modifier g in the regular expression.

Replace () method

Perform the search and replace functions. The first argument is a regular expression, and the second argument is the string to be replaced.

If the modifier g is specified, all occurrences are replaced, or only the first one is replaced.

Also, as mentioned in the previous article, regular expressions are grouped using parentheses, and the enclosed content is numbered from left to right. If the $ plus number appears in the replacement string, replace () replaces the two characters with text that matches the specified word expression. Like what:

var quote =/"([^"]*) "/g; ' abc "XXX" Def '. Replace (quote, ' "$");//abc "XXX" def

In addition, the second parameter of replace can also be a function. For example:

Text.replace (/\b\w+\b/g, function (word) {return word.substring (0,1). toUpperCase + word.substring (1);})
Match () method

The only parameter is the regular expression, which returns an array of matches. If G is set, returns an array of all occurrences.

Also, if there is no modifier g, the first item in the returned array is a matching string, followed by an item that is enclosed in parentheses in the regular expression.

Like what:

var url =/(\w+): \/\/([\w.] +) \/(\s*)/;
var text = ' Visit my blog http://www.example.com/~david ';//[' http://www.example.com/~david ', ' http ', ' www.example.com ' , ' ~david ']
Split () method

The parameters of split also support regular expressions.

RegExp Object
    • Five properties of RegExp

Source: Text of regular expression
Global: Do you have modifier g
IgnoreCase: Is there a modifier i
Multiline: Is there a modifier multiline
LastIndex: If there is a modifier g, this property stores the next location to start the retrieval.

    • Two methods

The exec () method, similar to match, but always returns a result and returns information about the Lastindex property. The Exec method can then be called repeatedly to get all the matches.

The test () method is simpler than exec and returns true if a matching result is included.

Regular expressions in JavaScript

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.