Js Regular Expression basic syntax (essence), js Regular Expression

Source: Internet
Author: User
Tags date1 valid email address

Js Regular Expression basic syntax (essence), js Regular Expression

1. Regular Expression basic syntax

Two special symbols '^' and '$ '. They indicate the start and end of a string respectively.

Example:

"^ The": indicates all strings starting with "The" ("There", "The cat", etc );

"Of despair $": indicates the string ending with "of despair;

"^ Abc $": indicates that the start and end of the string are "abc"-Haha, only "abc" itself;

"Notice": indicates any string containing "notice.

As in the last example, if you do not use two special characters, you are indicating that the string to be searched is in any part of the searched string-you and
Do not place it on a certain top.

Others include '*', '+', and '? 'These three symbols indicate the number of repeated occurrences of one or more characters.

They indicate "none or more", "one or more", and "none or one ".

The following are examples:

"AB *": indicates that a string has one a followed by zero or several B. ("A", "AB", "abbb ",......);

"AB +": indicates that a string is followed by at least one B or more;

"AB? ": Indicates that a string has one a followed by zero or one B;

"? B + $ ": indicates that there are zero or one a followed by one or several B at the end of the string.

You can also use a range enclosed in braces to indicate the range of repeated times.

"AB {2}": indicates that a string has a followed by two B ("abb ");

"AB {2,}": indicates that a string contains at least two B strings;

"AB {3, 5}": indicates that a string has 3 to 5 B following.

Note that you must specify the lower limit of the range (for example, "{0, 2}" instead of "{, 2 }").

Also, you may have noticed that '*', '+' and '? 'Is equivalent to "{0,}", "{1,}", and "{0, 1 }".

There is also a 'region', which indicates "or" Operation:

"Hi, hello": indicates that a string contains "hi" or "hello ";

"(B effeccd) ef": "bef" or "cdef ";

"(A between B) * c": represents a string of "a" "B" mixed strings followed by a "c ";

'.' Can replace any character:

"A. [0-9]": indicates that a string has a "a" followed by an arbitrary character and a number;

"^. {3 }$": represents a string of any three characters (Length: 3 characters );

Square brackets indicate that certain characters can appear at a specific position in a string:

"[AB]": indicates that a string has a "a" or "B" (equivalent to "a between B ");

"[A-d]": indicates that a string contains one of the lower-case 'A' to 'D' (equivalent to "a character B character c character d" or "[abcd]");

"^ [A-zA-Z]": a string that starts with a letter;

"[0-9] %": indicates a digit before the percent sign;

", [A-zA-Z0-9] $": represents a string ending with a comma followed by a letter or number.

You can also use '^' in square brackets to indicate unwanted characters. '^' should be the first character in square brackets.

(For example, "% [^ a-zA-Z] %" indicates that no letter should appear in two percentage signs ).

In order to express it word by word, you must "^. $ () then * +? {\ "Are preceded by the transfer character '\'.

Note that escape characters are not required in square brackets.

2. Regular Expression verification control text box input character type

1. Only numbers and English letters can be entered:

<input onkeyup="value=value.replace(/[\W]/g,'') " onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\d]/g,''))" ID="Text1" NAME="Text1">

2. Only numbers can be entered:

<input onkeyup="value=value.replace(/[^\d]/g,'') " onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\d]/g,''))" ID="Text2" NAME="Text2">

3. Only the fullwidth fields can be entered:

<input onkeyup="value=value.replace(/[^\uFF00-\uFFFF]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\uFF00-\uFFFF]/g,''))" ID="Text3" NAME="Text3">

4. Only Chinese characters can be entered:

<input onkeyup="value=value.replace(/[^\u4E00-\u9FA5]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\u4E00-\u9FA5]/g,''))" ID="Text4" NAME="Text4">

3. General description of Regular Expressions

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

// Check whether it is composed of digits

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

^ Indicates that the headers must match the rules followed by ^.

$ Indicates that the headers must match the rules that match the top $ character.

The content in [] is an optional character set.

[0-9] indicates that the character range is 0-9.

{} Indicates that the length of a numeric string is valid from 1 to 20, that is, the number of occurrences of characters in [0-9] ranges from 1 to 20.

/^ And $/are used in pairs to indicate that the entire string must fully match the defined rule, instead of matching only one substring in the string.

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

// Check Logon Name: You can enter only 5-20 strings starting with a letter, which can contain numbers, "_", and ".".

/^ [A-zA-Z] {1} ([a-zA-Z0-9] | [. _]) {} $/

^ [A-zA-Z] {1} indicates that the first character must be a letter.

([A-zA-Z0-9] | [. _]) {} indicates a string with a length of 4 to 9 characters starting from the second digit (because it follows the last expression, it must contain uppercase/lowercase letters, numbers, or special character sets [..

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

// Check user name: only 1-30 strings starting with letters can be entered

/^ [A-zA-Z] {1, 30} $/

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

// Password verification: only 6-20 letters, numbers, and underscores can be entered

/^ (\ W) {6, 20} $/

\ W: Used to match letters, numbers, or underscores

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

// Check the common phone number and fax number. It can start with "+" or a number and can contain "-" and "".

/^ [+] {0, 1} (\ d) {1, 3} []? ([-]? (\ D) | []) {1, 12}) + $/

\ D: Used to match numbers from 0 to 9;

"?" Metacharacter specifies that the leading object must appear zero or once consecutively in the target object

Matching strings include: + 123-999 999; + 123-999 999; 123 999 999; + 123 999999

**************************************** ***************************************
// Verify the URL

/^ Http [s] {0, 1 }:\/\/. + $/or/^ http [s] {0, 1 }:\/\/. {1, n }$/(the url string length is length ("https: //") + n)
\/: The character "/".

. Indicates the set of all characters

+ It is equivalent to {1,}, that is, 1 to infinity.

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

// Verify Chinese characters only
/

^ [\ U4E00-\ u9FA5] + $/

[\ U4E00-\ u9FA5]: it is estimated that it is the range of the Chinese character set.

The above expressions are all tested in the following javascript

Rule expression:

<Input type = "input" name = "regxStr" value = "> (expressions between input and output) <br>

Check string:

<Input type = "input" name = "str" value = ""> <input type = "button" name = "match" value = "match" onClick = "alert (regx (regxStr. value, str. value); "> </form> </body> 

4. Regular Expression table usage

"^ \ D + $" // non-negative integer (positive integer + 0)

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

"^ (-\ D +) | (0 +) $" // non-positive integer (negative integer + 0)

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

"^ -? \ D + $ "// integer

"^ \ D + (\. \ d + )? $ "// Non-negative floating point number (Positive 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] *) $ "// 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 consisting of 26 English letters

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

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

"^ [A-Za-z0-9] + $" // string consisting of digits and 26 letters

"^ \ W + $" // a string consisting of digits, 26 letters, or underscores

"^ [\ W-] + (\. [\ w-] +) * @ [\ w-] + (\. [\ w-] +) + $ "// email address

"^ [A-zA-z] +: // (\ w + (-\ w + )*)(\. (\ w + (-\ w + )*))*(\? \ S *)? $ "// Url

/^ (D {2} | d {4})-(0 ([1-9] {1}) | (1 [1 | 2]) -([0-2] ([1-9] {1}) | (3 [0 | 1]) $ // year-month-day

/^ (0 ([1-9] {1}) | (1 [1 | 2]) /([0-2] ([1-9] {1}) | (3 [0 | 1]) /(d {2} | d {4}) $ // month/day/year

"^ ([W-.] +) @ ([0-9] {1, 3 }. [0-9] {1, 3 }. [0-9] {1, 3 }.) | ([w-] + .) +) ([a-zA-Z] {2, 4} | [0-9] {1, 3}) (]?) $ "// Emil

"(D + -)? (D {4 }-? D {7} | d {3 }-? D {8} | ^ d {7, 8}) (-d + )? "// Phone number

"^ (D {1, 2} | 1dd | 2 [0-4] d | 25 [0-5]). (d {1, 2} | 1dd | 2 [0-4] d | 25 [0-5]). (d {1, 2} | 1dd | 2 [0-4] d | 25 [0-5]). (d {1, 2} | 1dd | 2 [0-4] d | 25 [0-5]) $ "// ip address

^ ([0-9A-F] {2}) (-[0-9A-F] {2}) {5} $ // Regular Expression of the MAC address

^ [-+]? \ D + (\. \ d + )? $ // Value Type Regular Expression

5. javascript Regular Expression Test

// Check whether it is composed of digits

function isDigit(s){var patrn=/^[0-9]{1,20}$/;if (!patrn.exec(s)) return falsereturn true}

// Check Logon Name: You can enter only 5-20 strings starting with a letter, which can contain numbers, "_", and ".".

function isRegisterUserName(s){var patrn=/^[a-zA-Z]{1}([a-zA-Z0-9]|[._]){4,19}$/;if (!patrn.exec(s)) return falsereturn true}

// Check user name: only 1-30 strings starting with letters can be entered

function isTrueName(s){var patrn=/^[a-zA-Z]{1,30}$/;if (!patrn.exec(s)) return falsereturn true}

// Password verification: only 6-20 letters, numbers, and underscores can be entered

function isPasswd(s){var patrn=/^(\w){6,20}$/;if (!patrn.exec(s)) return falsereturn true}

// Verify the phone number and fax number. The phone number can start with "+" and contain "-" in addition to numbers.

function isTel(s){//var patrn=/^[+]{0,1}(\d){1,3}[ ]?([-]?(\d){1,12})+$/;var patrn=/^[+]{0,1}(\d){1,3}[ ]?([-]?((\d)|[ ]){1,12})+$/;if (!patrn.exec(s)) return falsereturn true}

// Verify the mobile phone number. It must start with a number and can contain "-" in addition to a number.

function isMobil(s){var patrn=/^[+]{0,1}(\d){1,3}[ ]?([-]?((\d)|[ ]){1,12})+$/;if (!patrn.exec(s)) return falsereturn true}

// Verify the zip code

function isPostalCode(s){//var patrn=/^[a-zA-Z0-9]{3,12}$/;var patrn=/^[a-zA-Z0-9 ]{3,12}$/;if (!patrn.exec(s)) return falsereturn true}

// Verify the search keyword

function isSearch(s){var patrn=/^[^`~!@#$%^&*()+=|\\\][\]\{\}:;\'\,.<>/?]{1}[^`~!@$%^&()+=|\\\][\]\{\}:;\'\,.<>?]{0,19}$/;if (!patrn.exec(s)) return falsereturn true}function isIP(s) //by zergling{var patrn=/^[0-9.]{1,20}$/;if (!patrn.exec(s)) return falsereturn true} /********************************************************************************** FUNCTION: isBetween* PARAMETERS: val AS any value* lo AS Lower limit to check* hi AS Higher limit to check* CALLS: NOTHING* RETURNS: TRUE if val is between lo and hi both inclusive, otherwise false.**********************************************************************************/function isBetween (val, lo, hi) {if ((val < lo) || (val > hi)) { return(false); }else { return(true); }}/********************************************************************************** FUNCTION: isDate checks a valid date* PARAMETERS: theStr AS String* CALLS: isBetween, isInt* RETURNS: TRUE if theStr is a valid date otherwise false.**********************************************************************************/function isDate (theStr) {var the1st = theStr.indexOf('-');var the2nd = theStr.lastIndexOf('-');if (the1st == the2nd) { return(false); }else {var y = theStr.substring(0,the1st);var m = theStr.substring(the1st+1,the2nd);var d = theStr.substring(the2nd+1,theStr.length);var maxDays = 31;if (isInt(m)==false || isInt(d)==false || isInt(y)==false) {return(false); }else if (y.length < 4) { return(false); }else if (!isBetween (m, 1, 12)) { return(false); }else if (m==4 || m==6 || m==9 || m==11) maxDays = 30;else if (m==2) {if (y % 4 > 0) maxDays = 28;else if (y % 100 == 0 && y % 400 > 0) maxDays = 28;else maxDays = 29;}if (isBetween(d, 1, maxDays) == false) { return(false); }else { return(true); }}}/********************************************************************************** FUNCTION: isEuDate checks a valid date in British format* PARAMETERS: theStr AS String* CALLS: isBetween, isInt* RETURNS: TRUE if theStr is a valid date otherwise false.**********************************************************************************/function isEuDate (theStr) {if (isBetween(theStr.length, 8, 10) == false) { return(false); }else {var the1st = theStr.indexOf('/');var the2nd = theStr.lastIndexOf('/');if (the1st == the2nd) { return(false); }else {var m = theStr.substring(the1st+1,the2nd);var d = theStr.substring(0,the1st);var y = theStr.substring(the2nd+1,theStr.length);var maxDays = 31;if (isInt(m)==false || isInt(d)==false || isInt(y)==false) {return(false); }else if (y.length < 4) { return(false); }else if (isBetween (m, 1, 12) == false) { return(false); }else if (m==4 || m==6 || m==9 || m==11) maxDays = 30;else if (m==2) {if (y % 4 > 0) maxDays = 28;else if (y % 100 == 0 && y % 400 > 0) maxDays = 28;else maxDays = 29;}if (isBetween(d, 1, maxDays) == false) { return(false); }else { return(true); }}}}/********************************************************************************* FUNCTION: Compare Date! Which is the latest!* PARAMETERS: lessDate,moreDate AS String* CALLS: isDate,isBetween* RETURNS: TRUE if lessDate<moreDate*********************************************************************************/function isComdate (lessDate , moreDate){if (!isDate(lessDate)) { return(false);}if (!isDate(moreDate)) { return(false);}var less1st = lessDate.indexOf('-');var less2nd = lessDate.lastIndexOf('-');var more1st = moreDate.indexOf('-');var more2nd = moreDate.lastIndexOf('-');var lessy = lessDate.substring(0,less1st);var lessm = lessDate.substring(less1st+1,less2nd);var lessd = lessDate.substring(less2nd+1,lessDate.length);var morey = moreDate.substring(0,more1st);var morem = moreDate.substring(more1st+1,more2nd);var mored = moreDate.substring(more2nd+1,moreDate.length);var Date1 = new Date(lessy,lessm,lessd); var Date2 = new Date(morey,morem,mored); if (Date1>Date2) { return(false);}return(true);}/********************************************************************************** FUNCTION isEmpty checks if the parameter is empty or null* PARAMETER str AS String**********************************************************************************/function isEmpty (str) {if ((str==null)||(str.length==0)) return true;else return(false);}/********************************************************************************** FUNCTION: isInt* PARAMETER: theStr AS String * RETURNS: TRUE if the passed parameter is an integer, otherwise FALSE* CALLS: isDigit**********************************************************************************/function isInt (theStr) {var flag = true;if (isEmpty(theStr)) { flag=false; }else{ for (var i=0; i<theStr.length; i++) {if (isDigit(theStr.substring(i,i+1)) == false) {flag = false; break;}}}return(flag);}/********************************************************************************** FUNCTION: isReal* PARAMETER: heStr AS String decLen AS Integer (how many digits after period)* RETURNS: TRUE if theStr is a float, otherwise FALSE* CALLS: isInt**********************************************************************************/function isReal (theStr, decLen) {var dot1st = theStr.indexOf('.');var dot2nd = theStr.lastIndexOf('.');var OK = true;if (isEmpty(theStr)) return false;if (dot1st == -1) {if (!isInt(theStr)) return(false);else return(true);}else if (dot1st != dot2nd) return (false);else if (dot1st==0) return (false);else {var intPart = theStr.substring(0, dot1st);var decPart = theStr.substring(dot2nd+1);if (decPart.length > decLen) return(false);else if (!isInt(intPart) || !isInt(decPart)) return (false);else if (isEmpty(decPart)) return (false);else return(true);}}/********************************************************************************** FUNCTION: isEmail* PARAMETER: String (Email Address)* RETURNS: TRUE if the String is a valid Email address* FALSE if the passed string is not a valid Email Address* EMAIL FORMAT: AnyName@EmailServer e.g; webmaster@hotmail.com* @ sign can appear only once in the email address.*********************************************************************************/function isEmail (theStr) {var atIndex = theStr.indexOf('@');var dotIndex = theStr.indexOf('.', atIndex);var flag = true;theSub = theStr.substring(0, dotIndex+1)if ((atIndex < 1)||(atIndex != theStr.lastIndexOf('@'))||(dotIndex < atIndex + 2)||(theStr.length <= theSub.length)) { return(false); }else { return(true); }}/********************************************************************************** FUNCTION: newWindow* PARAMETERS: doc -> Document to open in the new windowhite -> Height of the new windowwide -> Width of the new windowbars -> 1-Scroll bars = YES 0-Scroll Bars = NOresize -> 1-Resizable = YES 0-Resizable = NO* CALLS: NONE* RETURNS: New window instance**********************************************************************************/function newWindow (doc, hite, wide, bars, resize) {var winNew="_blank";var opt="toolbar=0,location=0,directories=0,status=0,menubar=0,";opt+=("scrollbars="+bars+",");opt+=("resizable="+resize+",");opt+=("width="+wide+",");opt+=("height="+hite);winHandle=window.open(doc,winNew,opt);return;}/********************************************************************************** FUNCTION: DecimalFormat* PARAMETERS: paramValue -> Field value* CALLS: NONE* RETURNS: Formated string**********************************************************************************/function DecimalFormat (paramValue) {var intPart = parseInt(paramValue);var decPart =parseFloat(paramValue) - intPart;str = "";if ((decPart == 0) || (decPart == null)) str += (intPart + ".00");else str += (intPart + decPart);return (str);}

"^ \ D + $" // non-negative integer (positive integer + 0)

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

"^ (-\ D +) | (0 +) $" // non-positive integer (negative integer + 0)

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

"^ -? \ D + $ "// integer

"^ \ D + (\. \ d + )? $ "// Non-negative floating point number (Positive 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] *) $ "// 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 consisting of 26 English letters

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

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

"^ [A-Za-z0-9] + $" // string consisting of digits and 26 letters

"^ \ W + $" // a string consisting of a number, 26 English letters, or underscores

"^ [\ W-] + (\\. [\ w-] +) * @ [\ w-] + (\\. [\ w-] +) + $ "// email address

"^ [A-zA-z] +: // (\ w + (-\ w + )*)(\\. (\ w + (-\ w + )*))*(\\? \ S *)? $ "// Url

The above is the basic regular expression syntax shared with you. I hope it will help you learn it.

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.