Common JavaScript Regular Expressions

Source: Internet
Author: User

Regular expressions are used for string processing, form verification, and other occasions. They are practical and efficient, but they are always not sure when used, so they often need to be checked online. I will add some frequently-used expressions to my favorites for memo.

Regular Expressions matching Chinese characters:

[\u4e00-\u9fa5]

Match double-byte characters (including Chinese characters ):

[^\x00-\xff]

Application: Calculate the length of a string (two-byte length Meter 2, ASCII character meter 1)

String.prototype.len=function(){ return this.replace([^\x00-\xff]/g,"aa").length; }

Regular Expression matching empty rows:

\n[\s|]*\r

Regular Expressions matching HTML tags:

/<(.*)>.*<\/\1>|<(.*) \/>/

Regular Expression that matches the beginning and end spaces:

(^\s*)|(\s*$)

Application: JavaScript does not have trim functions like vbscript. We can use this expression to implement it, as shown below:

String.prototype.trim = function(){    return this.replace(/(^\s*)|(\s*$)/g, "");}

The following is a Javascript program that uses regular expressions to match IP addresses and convert IP addresses to corresponding values:

Function IP2V (ip) {re =/(\ d + )\. (\ d + )\. (\ d + )\. (\ d +)/g // The regular expression that matches the IP address if (re. test (ip) {return RegExp. $1 * Math. pow (255, 3) + RegExp. $2 * Math. pow (255, 2) + RegExp. $3*255 + RegExp. $4*1} else {throw new Error ("Not a valid IP address! ")}}

However, if the above program does not use regular expressions, it may be easier to directly use the split function to separate them. The program is as follows:

Var ip = "10.100.0000168" ip = ip. split (". ") alert (" the IP value is: "+ (ip [0] * 255*255*255 + ip [1] * 255*255 + ip [2] * 255 + ip [3] * 1 ))

Match the regular expression of the Email address:

\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

The regular expression matching the URL:

http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?

Algorithm program that uses regular expressions to remove repeated characters in a string: [* Note: This program is incorrect]

Var s = "abacabefgeeii" var s1 = s. replace (/(.). * \ 1/g, "$1") var re = new RegExp ("[" + s1 + "]", "g") var s2 = s. replace (re, "") alert (s1 + s2) // The result is: abcefgi ================================ if var s = "abacabefggeeii" result no, the result is: the regular expression of abeicfgg has limited capabilities ================================

One expression to remove repeated characters: The idea is to use the backward reference to retrieve repeated characters, and then create a second expression with repeated characters to get non-repeated characters, connect the two. This method may not apply to strings with character order requirements. Javascript programs that extract file names from URLs using regular expressions. the following result is page1.

s="http://blog.penner.cn/page1.htm"s=s.replace(/(.*\/){ 0, }([^\.]+).*/ig,"$2")alert(s)

Use regular expressions to restrict text box input in a webpage form:

You can only enter Chinese characters using regular expressions:

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

You can only enter full-width characters using regular expressions:

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

You can only enter numbers using regular expressions:

onkeyup="value=value.replace(/[^\d]/g,'') "onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\d]/g,''))"

You can only enter numbers and English letters using regular expressions:

onkeyup="value=value.replace(/[\W]/g,'') "onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\d]/g,''))"

Match a non-negative integer (positive integer + 0)

^\d+$

Match a positive integer

^[0-9]*[1-9][0-9]*$

Match non-positive integers (negative integers + 0)

^((-\d+)|(0+))$

Match a negative integer

^-[0-9]*[1-9][0-9]*$

Matching integer

^-?\d+$

Match non-negative floating point number (Positive floating point number + 0)

^\d+(\.\d+)?$

Match Positive floating point number

^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$

Match non-Positive floating point number (negative floating point number + 0)

^((-\d+(\.\d+)?)|(0+(\.0+)?))$

Match negative floating point number

^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$

Match floating point number

^(-?\d+)(\.\d+)?$

Match a string consisting of 26 English letters

^[A-Za-z]+$

Matches a string consisting of 26 uppercase letters.

^[A-Z]+$

Match a string consisting of 26 lower-case letters

^[a-z]+$

Match strings consisting of digits and 26 English letters

^[A-Za-z0-9]+$

Match a string consisting of digits, 26 English letters, or underscores

^\w+$

Matching email address

^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$

Matching url

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

Matching html tags

<\s*(\S+)(\s[^>]*)?>(.*?)<\s*\/\1\s*>

Verify the valid email format: The following example uses the static Regex. IsMatch method to verify whether a string is in a valid email format. If the string contains a valid email address, the IsValidEmail method returns true; otherwise, the return value is false without any other operations. You can use IsValidEmail to filter out email addresses that contain invalid characters before the application stores the addresses in the database or displays them on the ASP. NET page.

bool IsValidEmail(string strIn){// Return true if strIn is in valid e-mail format.return Regex.IsMatch(strIn, @"^([\w-\.]+)@((\[[0-9]{ 1,3 }\.[0-9]{ 1,3 }\.[0-9]{ 1,3 }\.)|(([\w-]+\.)+))([a-zA-Z]{ 2,4 }|[0-9]{ 1,3 })(\]?)$");}

Clear input string: the following code example uses the static Regex. Replace method to extract invalid characters from the string. You can use the CleanInput method defined here to clear potentially harmful characters that may be entered in the text field of the form that receives user input. CleanInput returns a string after all non-alphanumeric characters except @,-(hyphen), and. (period) are cleared.

String CleanInput(string strIn){    // Replace invalid characters with empty strings.    return Regex.Replace(strIn, @"[^\w\.@-]", "");}

Change Date Format: the following code uses the Regex. Replace method to Replace the date format of mm/dd/yy with the date format of dd-mm-yy.

String MDYToDMY(String input){    return Regex.Replace(input,"\\b(?<month>\\d{ 1,2 })/(?<day>\\d{ 1,2 })/(?<year>\\d{ 2,4 })\\b","${ day }-${ month }-${ year }");}

This example shows how to use a named reverse reference in the Replace mode of Regex. Replace. Here, the replace expression $ {day} is inserted (?...) The substring captured by the Group. There are several static functions that allow you to operate using regular expressions without creating explicit Regular Expression objects. The Regex. Replace function is one of them. If you do not want to retain the compiled regular expression, this will bring you convenience.

Extract URL Information: The following code example uses Match. Result to extract protocol and port number from URL. For example, "http://www.penner.cn: 8080 ...... "Http: 8080" is returned ".

String Extension(String url){    Regex r = new Regex(@"^(?<proto>\w+)://[^/]+?(?<port>:\d+)?/",    RegexOptions.Compiled);    return r.Match(url).Result("${ proto }${ port }");}

Only letters and numbers, no less than 6 digits, and the regular expression of the password contained in both numbers and letters can be expressed in C:

\w{ 6 }(\w+)*

An algorithm program that splits the path string into the root directory and sub-directories. The path formats include C: \ aa \ bb \ cc, \ aa \ bb \ cc, the ftp://aa.bb/cc above path will be split into: C: \ and aa \ bb \ cc, \ aa and \ bb \ cc, ftp: // and aa. bb/cc is implemented using javascript as follows:

var strRoot,strSubvar regPathParse=/^([^\\^\/]+[\\\/]+|\\\\[^\\]+)(.*)$/if(regPathParse.test(strFolder)){    strRoot=RegExp.$1    strSub=RegExp.$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.