JavaScript Regular Expression Basics Summary

Source: Internet
Author: User
Tags character classes

Regular Expressions: Find, replace, and fetch operations on information in a string. (comments and whitespace are not supported, must be written in one line)
Creation of regular Expressions: characters that are contained between a pair of slashes (direct amount syntax)
For example:
var pattern =/s$/; Creates a regular to match all strings that end with the letter S and assigns a value to the pattern

first, the character class:
The character class is formed by placing the direct volume characters in square brackets alone.
A character class can match any character it contains.
character classes for regular expressions:
[...] 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 that consists of any ASCII character is equivalent to [a-za-z0-9]
\w A word that consists of any non-ASCII character is equivalent to [^a-za-z0-9]
\s Any Unicode whitespace character
\s any non-Unicode whitespace characters
\d any ASCII number equivalent to [0-9]
\d Any non-ASCII number equivalent to [^0-9]
[\b] backspace direct volume (special case)
For example: The/[a,b,c]/expression matches any one of the letters A,B,C
/[\s\d]/to match any white space character or number

Second, repeat:
The token used to denote the repetition of the specified character
repeating character syntax for regular expressions:
{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, 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, equivalent to {0,}

For example:/\d{2,4}/matches a number of
/\w{3}\d/exact Match of 3 words and an optional number

iii. selection, grouping, and referencing
Matching program: Left-to-right, if match on the left matches, automatically ignores the right match (even if a better match can be produced)
①| Used to separate the characters for selection
For example:/ab|cd|ef/can match the string "AB", "CD" or "EF"
/\d{3}| [A-z] {4}/matches 3 digits or four lowercase letters
② ()
Function One: Synthesize sub-expressions of individual items
Role two: Define sub-patterns in a complete pattern
When a regular expression succeeds and matches the target string, the part that matches the sub-pattern in parentheses can be drawn from the target string.
For example:
/[a-z]+\d+/retrieves one or more lowercase letters followed by one or more digits
If we are concerned with the number of each tail, we can put the numerical part of the pattern into parentheses (/[a-z]+ (\d)/) so that we can extract the numbers from the retrieved matches.
Function Three: Allows the introduction of the preceding subexpression at the back of the same regular expression
Implementation method: Add one or more digits after the character \ (this number specifies the position of the parenthesized sub-expression in the regular expression)
For example: \1 refers to the first parenthesized sub-expression
Note: The position is based on the position of the opening parenthesis of the participating count;
Regular expressions do not allow single quotes in double-quoted content, and vice-versa.
Summarize:
| Select to match the subexpression to the left of the character or to the right sub-expression
(...) Combine to combine several items into a single unit
(...?) Combine items into a single unit, but do not remember characters that match that group
\ n Matches the first occurrence of the nth grouping, the group is a subexpression in parentheses, and the group index is the left-to-right number of left brackets (?: This form of grouping does not participate in index encoding

Four, specify the location of the match:
Anchor: Specifies the legal location where the match occurred
^ matches the beginning of the string
$ matches the end of a string
\b matches the boundary of a word (in the position between \w and \w)
\b matches the position of a non-word boundary

Five, modifier:
Modifier is placed outside of//and does not appear between two lines/line
I is case insensitive
G Global match, find all matches, not stop after finding the first one
M multi-line matching

Vi. methods for pattern-matching string objects
Method One: Search () retrieves the location that matches it
Parameters: a Regular expression
Returns: The starting position of the first substring to match, and returns 1 if no matching substring is found
For example:

<script>    "JavaScript". Search (/script/i);      return value is 4 </script>

Note: ① If the parameter of search () is not a regular expression, it is converted to a regular expression by the RegExp constructor
②search () does not support global retrieval
method Two: replace () perform a search and replace operation
Parameters: first--Regular expression
The second--a string to be replaced (also a function that dynamically computes the replacement string)
Note: ① supports G,
G is set in the regular expression: all substrings matching the pattern are replaced with the string specified by the second argument
G not set in regular expression: replace only the first substring that matches
② If the first argument is not a regular, but a string, replace () will search directly for the string

For example, replace all case-insensitive JavaScript with a properly-case javascript

<script>    var str = "Javascript,javascript,javascript,javascript";    Alert (Str.replace (/javascript/gi, "JavaScript"));        Javascript,javascript,javascript,javascript</script>    

method Three: Match ()
Parameters: Regular Expressions
Return: An array of matching results
Support G
Example one:

<script>    var math = "1 plus 2 equals 3". Match (/\d+/g);    Console.log (math);     ["1", "2", "3"]    Console.log (typeof math);     Object</script>

Example two:

<script>    var math = "1 plus 2 equals 3". Match (/\d/);    Console.log (math);     ["1", index:0, Input: "1 plus 2 equals 3"]    Console.log (typeof math);     Object</script>    

Attention:
A non-global regular expression is passed to math () for the string:
Match condition: Only the first match is retrieved
return value: Array
The first element of the array: the matched string
The second element of the array: a subexpression enclosed in parentheses in the regular expression, with two properties for the returned array-->index and input

Method four: Split ()
return value: Array
Delimiter: Arguments for Split ()
For example:

<script>    var str= "1,2,3,4,5,6,7,8". Split (', ');    Console.log (str); ["1", "2", "3", "4", "5", "6", "7", "8"]</script>

When the parameter is a regular expression (you can specify a delimiter, allowing any number of whitespace characters to be left on either side)
Return: The string that is used to invoke it is split into an array of substrings

<script>    var str= "1,2,3,4,5,6,7,8". Split (/\s*,\s*/);     Allow any number of whitespace characters    Console.log (str) to be left on both sides;     ["1", "2", "3", "4", "5", "6", "7", "8"]</script>

Vii. Objects of REGEXP

RegExp () constructor:
Parameters: two string arguments
First: The body part of a regular expression (text between two slashes)
Second: (optional) Specifies the modifier for the regular expression (g,i,m or a combination of the three)
Note: Both string literals and regular expressions are prefixed with the/character as an interpreted character
For example:
var zipCode = new RegExp (' \\d{5} ', ' G '); Globally match 5 numbers in a string, note that this is a//rather than/

JavaScript Regular Expression Basics Summary

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.