23javascript Regular Expressions __ Regular expressions

Source: Internet
Author: User
Tags character classes first string alphanumeric characters
Regular expression parsing in JavaScript
A regular expression is an object that describes the character pattern, and the JavaScript RegExp object and string object define methods for performing powerful pattern matching and text abetting and substitution functions using regular expressions.


In JavaScript, a regular expression is represented by a RegExp object, and you can create a RegExp object in two ways:
One is to use the RegExp () constructor to create the RegExp object.


The other is text formatting. Use the newly added special syntax in javascript1.2 to create a RegExp object, just as a string literal is defined as a character enclosed in quotation marks, and the direct amount of the regular expression is defined as a character that is contained between a pair of slashes (/). So the JavaScript creation RegExp object might contain the following code:
var pattern=/s$/or var pattern=new RegExp ("s$");
This line of code creates a new RegExp object and assigns it to variable pattern. This particular RegExp object matches all strings that end with the letter "s".


A text format or regular expression constructor
Text Format:/pattern/flags
Regular expression constructor: New RegExp ("pattern" [, "flags"]);
Parameter description:
Pattern--a regular expression literal
Flags--if present, will be the following values:
G: Global Match
I: Ignore case
GI: Above combination
M: multiple-line matching
[note] The arguments in the text format do not use quotation marks, but the arguments that are used when using the constructor require quotes.


1 Direct measure characters
We have found that in regular expressions all alphabetic characters and numbers are matched by literal meaning to themselves. JavaScript Regular expressions also support some non-alphanumeric characters by escaping sequences that begin with a backslash (\).
For example, the sequence "\ n" matches a literal newline character in a string. In regular expressions, many punctuation marks have special meanings. Here are the characters and their meanings:
\ F Page Feed
\ n Line Feed
\ r Carriage Return
\ t tab
\ v Vertical Tab
\/One/Direct quantity
\ \ A \ Direct quantity
\ . One. Direct quantity
* A * Direct quantity
\ + A + direct quantity
\ ? One? Direct quantity
\ | One | Direct quantity
\ (One (direct quantity
) A direct amount
\ [one [Direct quantity
\] A direct amount
\ {a {Direct amount
\} A direct amount
\-one-direct volume
\ XXX ASCII code characters specified by decimal number xxx
\ xnn ASCII code characters specified by the hexadecimal number nn
\ CX control character ^x. For example, \ci is equivalent to \ t, \CJ is equivalent to \ n
If you want to use special punctuation marks in regular expressions, you must precede them with a "\".


^ matches the beginning of a character, and in multiple-line retrieval, it matches the beginning of a line
The $ match is the end of the character, and in multiple-row retrieval, the match is the end of a line
\b matches the boundary of a word. In short, the position between the character \w and the \w (note: [\b] matches backspace)
\b A character that matches the bounds of a non-word


2 Character classes
You can combine individual direct characters into a character class by putting them in brackets. A character class matches any of the characters it contains, so the regular expression/[ABC]/And the letter "a", "B", and "C" all match. In addition, you can define a negative character class, These classes match all characters except those contained within the brackets. To define a negative character class, you use a ^ symbol as the first character from the left bracket.


Character classes for regular expressions:
[...] Any character located within the parentheses. such as: [ABC]
[^...] Any character that is not in parentheses. such as: [^ABC]
. Any single character other than the newline character, equivalent to [^\n]
\w any single word character, equivalent to [a-za-z0-9]
\w any non-word character, equivalent to [^a-za-z0-9]
\s any whitespace, equivalent to [\ t \ n \ r \ f \ V]
\s any non-white-space character, equivalent to [^\ t \ n \ r \ f \ V]
\d any number, equivalent to [0-9]
\d any character other than a number, equivalent to [^0-9]
[\b] A backspace direct amount (special case)
| The basic meaning of an operator is or an operation. T (A|e|i|oo) n indicates that the Tan,ten,tin,toon can be matched.
(...) Represents a grouping in a regular expression. Divide several items into one unit. This unit can be made by *, +,. and | symbols, and you can also remember characters that match this group for later reference use
\ n matches the characters that are matched by the nth group. Grouping is a subexpression in parentheses (which may be nested). The group number is a left to right count of the number of left parentheses


Matches any character, including line breaks, and the following is the correct arbitrary word single-character expression matching rule:
([\s\s]*)
It can also be represented by "([\d\d]*)", "([\w\w]*)".




3 symbols that indicate the number of matches
{n, m} matches the previous item at least n times, but not more than m times
{n,} matches n times before, or multiple
{n} matches the previous item exactly n times
? Matches the previous item 0 or 1 times, which means the previous item is optional. Equivalent to {0, 1}
+ matches 1 or more times before, equivalent to {1,}
* Match the previous item 0 or more times. Equivalent to {0,}
For example:
/\d{2, 4}/matches numbers between 2 and 4.


/\W{3} \d?/matches three single characters and an arbitrary number.


/\s+java\s+/matches the string "Java" and can have one or more spaces before and after it.


/[^ "] */Match 0 or more non-quote characters.




4 the properties of the regular expression
The syntax for regular expressions also has the last element, that's the property of the regular expression, which shows the rules for advanced pattern matching. Unlike other regular expression syntaxes, attributes are described outside of the/symbol. That is, they do not appear between the two slashes, but are positioned after the second slash. JavaScript 1.2 supports two properties.
Attribute I shows that pattern matching should be case insensitive.
Attribute g indicates that pattern matching should be global. That is, performing a global match, in short, is to find all the matches, rather than stopping after the first one is found. These two properties combine to perform a global, case-insensitive match.


Static properties
The Index property. is the starting position of the first match for the current expression pattern, counting starting at 0. The initial value is-1, and the Index property will change each time a successful match is made.


The input property. Returns the currently acting string, which can be abbreviated to $_, and the initial value is an empty string "".


Lastindex property. Is the next position of the last character in the first match of the current expression pattern, counting from 0, often as the starting position for the search, with an initial value of-1, which indicates that the search starts at the starting position, and the Lastindex property value changes each time a successful match is made.


Lastmatch property. is the last matching string for the current expression pattern, which can be abbreviated to $&. Its initial value is an empty string "". The value of the Lastmatch property changes each time a successful match is made.


5 Methods of regular expressions
Test () method
RegExp object instance. Test (String)
Return value: Returns true if the regular rule defined in the RegExp instance is met, otherwise it returns false.


EXEC () method
RegExp object instance. Exec (String)
Return value: An array returns an array of results if the matching text is found by exec (). Otherwise, NULL is returned. The No. 0 element of this array is the text that matches the regular expression first, and if RegExp is not grouped, the returned array contains only the No. 0 element, and if there are groupings in RegExp, the 1th element of the returned array is the text (if any) that matches the 1th grouping of Regexpobject. , the 2nd element is the text that matches the 2nd group of Regexpobject (if any), and so on. In addition to the array elements and length properties, the Exec () method returns two properties. The Index property declares the position of the first character of the matching text. The input property holds a string that is retrieved. We can see that when calling the Exec () method of a Non-global RegExp object, the returned array is the same as the array returned by the calling Method String.match ().


However, when Regexpobject is a global regular expression G, the Exec () behavior is slightly more complex. It starts retrieving string strings at the character specified by the Regexpobject lastindex property. When exec () finds the text that matches the expression, after the match, it sets the Regexpobject lastindex property to match the next position of the last character in the text. This means that you can iterate through all the matching text in a string by repeatedly calling the Exec () method. When exec () can no longer find the matching text, it returns null and resets the Lastindex property to 0.
Note: If you start retrieving a new string after a pattern match completes in one string, you must manually reset the Lastindex property to 0.



String Object method:
Match () Method:
Usage: string object. Match (RegExp object)
return value: Array
The match () method retrieves the string stringobject to find one or more text that matches the regexp. The behavior of this method depends to a great extent on whether the regexp has a sign G.


If RegExp does not have a flag G, then the match () method can only perform a match in Stringobject. If no matching text is found, match () returns NULL. Otherwise, it returns an array that holds information about the matching text it finds. The No. 0 element of the array holds the text that matches the regular expression, and if regexp exists, the 1th element that returns the array is the text that matches the 1th group of Regexpobject (if any), and the 2nd element is the regexpobject of the 2nd group. With the text (if any), and so on. In addition to these regular array elements, the returned array also contains two object properties. The Index property declares the position of the starting character of the matching text in the Stringobject, and the input property declares a reference to the Stringobject.


If RegExp has a flag G, the match () method performs a global search and finds all matching regular expression strings in the Stringobject. If no matching substring is found, NULL is returned. If one or more matching substrings are found, an array is returned. However, the contents of the array returned by the global match are very different from the former, and its array elements only hold all the matching regular expression strings in the Stringobject, and do not hold substrings that match the groupings in the regular expression. There is also no index attribute or input property.
Note: Under Global retrieval mode G, match () does not provide information about the text that matches the grouping, nor does it declare the position of each matching substring. If you need information for these global searches, you can use Regexp.exec ().


The following example shows the use of the match function method in javascript:
function Matchdemo () {
var r, re; Declare a variable.
var s = "The rain in Spain falls mainly in the plain";
re =/ain/i; Creates a regular expression pattern.
r = S.match (re); Try to match the search string.
return (R); Return to the place where "Ain" first appeared.
}
This example shows the use of the match function method in JavaScript with the G flag setting
function Matchdemo () {
var r, re; Declare a variable.
var s = "The rain in Spain falls mainly in the plain";
re =/ain/ig; Creates a regular expression pattern.
r = S.match (re); Try to match the search string.
return (R); The returned array contains all the "Ain"
Four matches that occurred.
}


Search () Method:
Usage: String object. Search (RegExp object)
Return value: The Search method indicates whether a corresponding match exists. If a match is found, the search method returns an integer value indicating the offset from the start of the matching distance string. If no match is found, return-1.
Note: Only the position of the first substring that matches the regular expression lookup content is returned. So it doesn't make sense to use global search parameters.


Replace () Method:
Usage: string object. replace (RegExp Object | string, "substituted string")
Return value: If the RegExp object's global match G is set, all satisfied will be replaced; returns the replacement string.
Note: You can also accept strings in replace, but only the first string that satisfies the condition.


*************************
The exec () method differs from the match () method:
1 for regular expressions that are not grouped
If the regular expression that executes the Exec method is not grouped (non-group is enclosed in parentheses), so if there is a match, he will return an array of only one element, the only element of which is the first string that matches the regular expression, or null if there is no match.


The following two alert functions pop up with the same information:
var str= "Cat,hat";
var p=/at/; No G attribute
Alert (p.exec (str))
Alert (Str.match (p))


Are "at". exec is equivalent to match in this situation.


But if the regular expression is a global match (g attribute), then the above code results are different:
var str= "Cat,hat";
var p=/at/g; Note the G property
Alert (p.exec (str))
Alert (Str.match (p))


respectively is
"At"
"At,at".


Because the regular expression exec that has no grouping returns only the first text that matches the regular expression, match returns all text that matches the regular expression when the regular expression specifies the G attribute.


2 for regular expressions that have groups
exec if a match is found and contains a grouping, the returned array will contain more than one element, the first element is the string that matches the regular expression found, followed by the first and second in the match ... A string that is grouped. (Reverse reference)


The code below will pop up "Cat2,at":
var str= "Cat2,hat8";
var p=/c (at) \d/;
Alert (p.exec (str))


The first element is the string "Cat2" that matches the/C (at) \d/, followed by the "at" of the matching grouping (at) in parentheses.






var sometext= "web2.0. net2.0";
var pattern=/(\w+) (\d) \. (\d)/g;
var outcome_exec=pattern.exec (Sometext);
var outcome_matc=sometext.match (pattern);


Analysis:
Outcome_exec value: The G attribute in pattern has no effect on the EXEC function, so exec will match the first string "web2.0" that can be matched as the first element of its return array, in addition to the pattern containing three groupings (\w+), (\d), (\d), so the array will also contain three elements, followed by "Web", "2", "0", so the end result of exec execution is: ["web2.0", "Web", "2", "0"]
OUTCOME_MATC value: Because pattern is a global match, match matches all substrings that match the regular expression, so the value of the resulting array outcome_matc to ["web2.0", "net2.0"]. If pattern does not have the G attribute, it will be the same as the outcome_exec result.


*************************












6 Common JS Regular expressions
JavaScript is used when validating forms


"^-[0-9]*[1-9][0-9]*$"//Negative integer


/^[0-9]*[1-9][0-9]*$///Positive integer


/^[1-9]{1}[0-9]{0,1}$///1~99


"^-?\d+$"//Integer


"^\d+ (\.\d+)? $"//nonnegative floating-point number (positive float + 0)


"^ ([0-9]+\. [0-9]*[1-9][0-9]*) | ([0-9]*[1-9][0-9]*\. [0-9]+) | ([0-9]*[1-9][0-9]*)] $ "//Positive floating-point number


"^ ((-\d+ (\.\d+)?) | (0+ (\.0+)) $ "//non-positive floating-point number (negative floating-point number + 0)


^ (-([0-9]+\. [0-9]*[1-9][0-9]*) | ([0-9]*[1-9][0-9]*\. [0-9]+) | ([0-9]*[1-9][0-9]*))] $ "//negative floating-point number


"^ (-?\d+) (\.\d+)? $"//floating-point number


"^[a-za-z]+$"//A string of 26 English letters


"^[a-z]+$"//A string of 26 uppercase letters


"^[a-z]+$"///a string consisting of 26 lowercase letters


"^[a-za-z0-9]+$"//A string of numbers and 26 English letters


"^\w+$"//A string of numbers, 26 English letters, or underscores


^[a-za-z]+:\/\/(\\w+ (-\\w+) *) (\ \\w+ (-\\w+) *) * (\\?\\s*) $//url


/calibration of ordinary telephone, fax number: You can "+" start, in addition to the number, can contain "-", the country number.
var patrn=/^ ([+]{0,1} (\d) {1,2}[-]?)? ((\d) {3,4} ([-]? \d) {6,9})) $/;


Regular expressions in YYYY/MM/DD hh:mm format
/^ (((1[6-9]| [2-9]\d) \d{2}) \/(0?[ 13456789]|1[012]) \/(0?[ 1-9]| [12]\d|30)] | (((1[6-9]| [2-9]\d) \d{2}) \/0?2\/(0?[ 1-9]|1\D|2[0-8]) | (((1[6-9]| [2-9]\d) (0[48]|[ 2468][048]| [13579] [26]) | ((16| [2468] [048]| [3579] [26]) )) (\/0?2\/29\/)) \s (0\d{1}|1\d{1}|2[0-3]):([0-5]\d{1}) $/


Regular Expressions for YYYY/MM/DD
/^ (((1[6-9]| [2-9]\d) \d{2}) \/(0?[ 13456789]|1[012]) \/(0?[ 1-9]| [12]\d|30)] | (((1[6-9]| [2-9]\d) \d{2}) \/0?2\/(0?[ 1-9]|1\D|2[0-8]) | (((1[6-9]| [2-9]\d) (0[48]|[ 2468][048]| [13579] [26]) | ((16| [2468] [048]| [3579] [26]) 00)) $/\/0?2\/29\/))




Regular Expressions for YYYY-MM-DD
/^(?:(?! 0000) [0-9]{4}-(?:(?: 0 [1-9]|1[0-2])-(?: 0 [1-9]|1[0-9]|2[0-8]) | (?: 0 [13-9]|1[0-2])-(?: 29|30) | (?: 0 [13578]|1[02])-31 | (?: [0-9]{2} (?: 0 [48]| [2468] [048]| [13579] [26]) | (?: 0 [48]| [2468] [048]| [13579] [26]) 00)-02-29 $/


Regular Expressions for Yyyy-mm-dd HH:mm:ss
/^(?:(?! 0000) [0-9]{4}-(?:(?: 0 [1-9]|1[0-2])-(?: 0 [1-9]|1[0-9]|2[0-8]) | (?: 0 [13-9]|1[0-2])-(?: 29|30) | (?: 0 [13578]|1[02])-31 | (?: [0-9]{2} (?: 0 [48]| [2468] [048]| [13579] [26]) | (?: 0 [48]| [2468] [048]| [13579] [26]) -02-29) \s+ ([01][0-9]|2[0-3]): [0-5][0-9]:[0-5][0-9]$/




Year 0001-9999, Format Yyyy-mm-dd or yyyy-m-d, hyphen can not be or "-", "/", "." One of them.
/^(?:(?! 0000) [0-9]{4} ([-/.]?) (?:(?: 0? [1-9]|1[0-2]) \1 (?: 0? [1-9]|1[0-9]|2[0-8]) | (?: 0? [13-9]|1[0-2]) \1 (?: 29|30) | (?: 0? [13578]|1[02]) \1 (?: 31)) | (?: [0-9]{2} (?: 0 [48]| [2468] [048]| [13579] [26]) | (?: 0 [48]| [2468] [048]| [13579] [26]) 00) ([-/.]?) 0?2\2 (?: 29)) $/




Time format HH
patternsdict.time_h=/^ (0\d{1}|1\d{1}|2[0-3]) $/;


Time Format hh:mm
patternsdict.time_hm=/^ (0\d{1}|1\d{1}|2[0-3]):([0-5]\d{1}) $/;


Time Format Hh:mm:ss
patternsdict.time_hms=/^ (0\d{1}|1\d{1}|2[0-3]): [0-5]\d{1}:([0-5]\d{1}] $/;


Match Show,show1 only. SHOW9, strings like "showddd" are not matched.
^show[1-9]?$




Regular expression IP address
var ipaddress = 20.26.43.111;
var re =/^ ([0-9]|[ 1-9]\D|1\D\D|2[0-4]\D|25[0-5]) \. ([0-9]| [1-9]\d|1\d\d|2[0-4]\d|25[0-5]) \. ([0-9]| [1-9]\d|1\d\d|2[0-4]\d|25[0-5]) \. ([0-9]| [1-9]\d|1\d\d|2[0-4]\d|25[0-5]) $/;
if (!re.test (IPAddress)) {
Alert ("Incorrect IP address format, please modify");
return false;
}




Regular expression Validation email format
function Testmail (mail,mess) {
Verifying email functions
var M=jquery.trim ($ ("#" +mail). attr (' value '));
var vm=new RegExp ("^[a-za-z0-9]{1,}@{1}[a-za-z0-9]{1,}\.{ 1}[a-za-z0-9]{3,}$ "," I "); Host name not with _ or-
var vm=new RegExp ("^[a-za-z0-9]{1,}?@{1}[a-za-z0-9]{1,}[a-za-z0-9_\-]*" (\.{ 1}[a-za-z0-9]{2,}) +$ "," I ");//Host name with _ or-
if (Mail.match (VM)) {
$ ("#" +mail). Next (). Remove ();
}else{
$ ("#" +mail). Next (). Remove ();
$ ("#" +mail). After ("&nbsp<span>" +mess+ "</span>");
}
}


The regular expression validates the URL format:
function Checkurl (TT) {
var url= "http://" +$ (TT). Val ();
alert (URL);
var reg=/^http:\/\/(\w+) ([_|.| \-|\/|\\]? (\w+)) *$/;
if (Url.match (reg)) {
Alert ("true");
return true;
}else{
Alert ("KKKK");
$ (this). Parent (). Find (": Last"). empty ();
$ (this). Parent (). Find (": Last"). Append ("Please fill in the correct site name!");
return false;
}
}


Regular Expressions validate Chinese characters (true as long as the characters you enter contain Chinese characters)
function Checkhanzi (TT) {
var hanzi=$ (TT). Val ();
Match Chinese characters
var reg=/[^\x00-\xff]/


if (Hanzi.match (reg)) {
Alert ("true");
return true;
}else{
Alert ("KKKK");
$ (this). Parent (). Find (": Last"). empty ();
$ (this). Parent (). Find (": Last"). Append ("Please fill in the correct site name!");
return false;
}
}


Regular expression matching keyword cannot have special characters
var reg=/^[^@#!%$¥&^*+-,.? \\s=\|] +$/;
if (Url.match (reg)) {
Alert ("Special characters that do not contain spaces");
return true;
}else{
Alert ("KKKK");
$ (this). Parent (). Find (": Last"). empty ();
$ (this). Parent (). Found (": Last"). Append ("contains special characters!");
return false;
}
}


The keywords entered by the regular expression must be comma-delimited to only the alphanumeric characters:
var reg=/^ ([\w\d\u4e00-\u9fa5],?) +$/;
if (Url.match (reg)) {
Alert ("true");
return true;
}else{
Alert ("KKKK");
$ (this). Parent (). Find (": Last"). empty ();
$ (this). Parent (). Find (": Last"). Append ("Comma separated by commas!");
return false;
}
}




Only numbers can be entered
function Onlynumber (e) {
E = Window.event | | E
var k = E.keycode | | E.which;


if ((k==110) | | (k==190) | | (k==46) | | (k==8) | | (k>=48 && k<=57) | | (k>=96 && k<=105) | | (k>=37 && k<=40) | | (k==189)) {


}else if ((k==190) | | (k==110)) {
if (window.event)
Window.event.returnValue = false;
Else
E.preventdefault ();//for Firefox
}else{
if (window.event)
Window.event.returnValue = false;
Else
E.preventdefault ();//for Firefox
}
}
<input type= "text" onkeydown= "Onlynumber (event)"/>






/**
* Rounding
* V Value
* E Keep decimal place number
*/
function Rounddigits (v,e) {
var t=1;
for (; e>0;t*=10,e--);
for (; e<0;t/=10,e++);
Return Math.Round (v*t)/t;
}
Alert (Rounddigits (12.5656565,2));

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.