javascript--Regular Expressions

Source: Internet
Author: User

1. Regular expressions
is an object that describes the character pattern.
1. How to create
1) Direct amount of regular expression
var pattern =/s$/;
2) RegExp () constructor
var pattern = new RegExp ("S $");
2. Direct volume characters
All letters and numbers in a regular expression are matched by literal meanings.
Character matching
-----------------------
Letters and numbers themselves
\ t tab
\ n line break
\v Vertical Tab
\f Page Break
\ r return character
\xnn the Latin character specified by the hexadecimal number nn \x0a = \ n
\uxxxx Unicode characters specified by hexadecimal xxxx, such as \u0009 = \ t
\CX control character ^x, for example \CJ equivalent to page break \ n
3. Character classes
The character class is formed by placing the direct volume character in square brackets alone. A character class can match any of its contained characters.
[...] Any character in square brackets
[^...] Any character that is not in square brackets
Special character Classes
. Any character except newline characters and other Unicode line terminators
\w any ASCII character, equivalent to [a-za-z0-9]
\w any non-ASCII character, equivalent to [^a-za-z0-9]
\s any Unicode whitespace characters: spaces, tabs, enter
\s Characters of any non-Unicode whitespace character
\d any ASCII number, equivalent to [0-9]
\d any character other than a non-ASCII number, equivalent to [^0-9]
[\b] backspace direct volume (special case)

4. Repetition must be used after the sub-expression
{N,m} matches the previous item at least n times, but no more than m times
{N,} matches the previous item n or more times
{n} matches the previous item n times
? Matches the previous item 0 or 1 times, equivalent to {0,1}
+ Match Previous item 1 or more times, equivalent to {1,}
* matches the previous item 0 or more times, equivalent to {0,}

For example:
/[abc]/matches any character in "a" "B" "C"
/[^abc]/matches any character other than "a" "B" "C"
/\d{2,4}/match four digits
/\w{3}\d?/matches three characters or an optional number
/\s+java\s+/string "Java" with one or more spaces before and after matching

5. Repeating mode
Greedy repetition
Matches the repeating character when it matches as much as possible
Non-greedy repetition
In the word to be matched specifier follow a question mark:?? +? *? {1,5}?
For example:
/a+/can match one or more consecutive letters a, and when "AAA" is used as a matching string, the regular expression matches its three characters
/a+?/can match one or more consecutive letters a, but match as little as possible. Matches only the first a
6. Select
Use the character ' | ' to split the selected character. The selection attempts to match the order from left to right until a match is found, and if the left selection matches, the right match is ignored, even if it produces a better match. /ab|cd|ef/can match "AB" or "CD" or "EF"
7. Grouping
"()" Effect:
1) combine individual items into sub-expressions
So that you can use the "|" as a unit. *""+""?" To process items within a cell
/java (script)/can match string Java, the following script can have or can not
/(AB|CD) +|ef/can match "EF" or "AB" "CD" one or more times
2) Define sub-patterns in full mode
When a regular expression succeeds in matching the target string, the part that matches the sub-patterns in the parentheses can be drawn from the target strings.
/[a-z]+\d+/one or more lowercase letters followed by one or more digits
(/[a-z]+ (\d+)/) You can extract the numbers at the end of each match
3) refer to the preceding subexpression after the same regular expression.
\1 referencing the first parenthesized sub-expression
/([Jj]ava ([Ss]cript)?) \sis\s (fun\w*)/\2 reference ([Ss]cript)
A reference to the previous subexpression in a regular expression, not a reference to a subexpression pattern, but a reference to the text that matches that pattern
For example:
/[' "][^ '"]*[' "]/matches 0 or more characters in single quotation marks or double quotes, but it does not require that the left and right quotes match
/([' "]) [^ ']]*\1/matches 0 or more characters in single quotation marks or double quotes, but it requires the quotation marks on the left and right to match

8. Specify a matching location
^ matches the beginning of a string, in a multi-row search, matches the beginning of a line
$ matches the end of a string, in multiple-row retrieval, matches the end of a line
\b matches the boundary of a word, that is, the position between the character \w and \w, or between the character \w and the beginning or end of the string.
\b matches the position of a non-word boundary
(? =p) 0 Wide forward assertion that requires the next character to match p, but cannot include those characters that match P
(?! P) 0 Wide negative lookahead assertion, requires that the next character does not match p
9. Modifiers
Does not appear between the two slashes, but appears after the second diagonal line.
New RegExp ("", "IgM")
I description match pattern match is case insensitive
G indicates that pattern matching should be global
M is used to perform the match in multiline mode.
/java$/im can match "Java" or "Java\nis fun"

2. String support for regular expressions in JavaScript
1. Search ()
The parameter is a regular expression. If the argument is not a regular expression, it is first converted to a constructor by RegExp. Global retrieval is not supported, returns the position of the first substring to match, and returns 1 if no matching substring is found.
"JavaScript". Search (/script/i); Returns 4
2. Replace ()
Used to perform a search and replace operation. The first argument is a regular expression, and the second argument is the string to replace.
Text.replace (/javascript/gi, "JavaScript"); Convert all JavaScript to JavaScript, case insensitive
3. Match ()
The most commonly used regular expression method, the parameter is a regular expression. Returns an array that consists of matching results.
When there is no G modifier in the regular expression, it is not a global match. At this point, the first element of the array is a matching string, and the remaining elements are sub-expressions enclosed in parentheses in the regular expression. If the regular expression is set to the modifier g, the array returned by the method contains all the matching results in the string.
"1 plus 2 equals 3". Match (/\d+/g)//Return ["1", "2", "3"]

var url =/(\w+): \/\/([\w.] +) \/(\s*)/;
var text = "Visit my blog at Http://www.briup.com/~ee";
var result = Text.match (URL);
if (result!=null) {
var fullurl = result[0];
var protocol = result[1];
var host = result[2];
var path = result[3];
}
4. The split () method is used to split a string into an array of strings.

Syntax: Stringobject.split (separator (required). A string or regular expression that splits stringobject from where specified by the parameter. ),howmany (optional))
The return value is a string array parameter can be a regular expression
"1, 2, 3, 4, 5". Split (/\s*,\s*/); ["1", "2", "3", "4", "5"] allow whitespace left and right on both sides of the delimiter

"2:3:4:5". Split (":")//will return ["2", "3", "4", "5"]
"|a|b|c". Split ("|") will return ["", "a", "B", "C"]

"Hello". Split ("")//Can return ["H", "E", "L", "L", "O"]

"Hello". Split ("", 3)//Returns a subset of the characters, use the Howmany parameter to return ["H", "E", "L"]

3. JavaScript in RegExp
1. Constructors
The first parameter includes the body part of the regular expression, which is the text between two slashes in the direct amount of the regular expression
The second parameter specifies the modifier of a regular expression. can only pass in G, i,m or its combination, omit
var zipcode = new RegExp ("/\d{5}", "G");
2. Properties
Source contains regular expression text
Global Boolean value indicating whether the regular expression has a modifier g
A Boolean value that indicates whether the regular expression has a modifier i ignoreCase
A Boolean value that indicates whether the regular expression has a modifier m multiline
LastIndex if the matching pattern has G, this property is stored at the beginning of the next retrieval of the entire string, which is called by the exec (), the test () method to the
3. Methods
1) EXEC ()
Similar to match. The argument is a string. Executes a regular expression on a specified string that performs a matching search in a string, returns null if no match is found, and returns an array if a match is found. The first element in the array element contains substrings that match the regular expression, and the remaining elements are substrings that match the subexpression within the parentheses. When the called regular expression object has the modifier g, it sets the Lastindex property of the current regular expression object to the character position next to the matching substring, and when the same regular expression calls exec () for the second time, it starts the retrieval from the character that the Lastindex property refers to. If there is no match to any result, reset the lastindex to 0.

var pattern =/java/ig;
var text = "JavaScript is more fun than java_is good";
var result;
while (result = pattern.exec (text))!=null) {
Console.log (result[0]+ "at" +result.index);
}
2) test ()
The argument is a string. Detects a string with test () and returns true if a matching result of the regular expression is included. Call Test () and call the exec () behavior equivalent, test () retrieves a string from the lastindex at the specified position, if it finds a matching result, Immediately sets lastindex to the end position of the current matching string.

var pattern =/java/ig;
var text = "JavaScript is more fun than java_is good";
var pattern.test (text); Result true
Unlike test () exec (), the String method search () replace () match () does not use the Lastindex property

javascript--Regular Expressions

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.