Common Regular Expressions

Source: Internet
Author: User
Tags alphanumeric characters

Regular expressions are used for string processing, form verification, and other occasions, practical and efficient, but always used to be not too sure, so often to surf the internet. I've collected some of my favorite expressions here, and I'm using them as a reminder.  This post will be updated at any time. Regular expressions that match Chinese characters: [\U4E00-\U9FA5]

Match double-byte characters (including kanji):

[^\x00-\xff]

Application: Calculates the length of a string (a double-byte character length meter 2,ascii character 1)

String.prototype.len=function () {return This.replace ([^\x00-\xff]/g, "AA"). Length;

Regular expression that matches a blank line:

\n[\s|] *\r

Regular expressions that match HTML tags:

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

Regular expression matching the leading and trailing spaces:

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

Application: There is no trim function like V bscript in J Avascript, we can use this expression to implement, as follows:

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

Decomposition and transformation of IP addresses using regular expressions
The following is a JavaScript program that matches an IP address with a regular expression and translates an IP address into a corresponding value:

function IP2V (IP)
{
re=/(\d+) \. (\d+) \. (\d+) \. (\d+)/g//matching regular expressions for IP addresses
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, the above program without regular expression, and directly with the split function decomposition may be more simple, the program is as follows:

var ip= "10.100.20.168"
Ip=ip.split (".")
Alert ("IP value is:" + (IP[0]*255*255*255+IP[1]*255*255+IP[2]*255+IP[3]*1))

Regular expression that matches the email address:

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

Regular expression to match URL URL:

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

Algorithm program for removing repeated characters in a string using regular expressions: [* Note: This program is incorrect]

var s= "Abacabefgeeii"
var s1=s.replace (/(.). *\1/g, "$")
var re=new RegExp ("[" +s1+ "]", "G")
var s2=s.replace (Re, "")
Alert (S1+S2)//Result: ABCEFGI

* Note
===============================
If var s = "Abacabefggeeii"
The result is not right, the result is: ABEICFGG
Limited ability to regular expressions
===============================

I used to post on the csdn to find an expression to implement the method of removing the repeated characters, which was not found, which is the simplest implementation I can think of. The idea is to use a back-to-reference to remove a repeating character, create a second expression with a repeating character, and take a concatenation of the characters that are not duplicated. This method may not be applicable for strings that require a character order.

A JavaScript program that uses a regular expression to extract the filename from the URL address, as shown in Page1

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

Use regular expressions to restrict the entry of text boxes in Web Forms:

Use regular expression restrictions to enter only Chinese:

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 with regular expression restrictions:

Onkeyup= "Value=value.replace (/[^\uff00-\uffff]/g, ')" onbeforepaste= "Clipboarddata.setdata (' text ', Clipboarddata.getdata (' text '). Replace (/[^\uff00-\uffff]/g, ')) "

You can only enter numbers with regular expression restrictions:

Onkeyup= "Value=value.replace (/[^\d]/g, ')" onbeforepaste= "Clipboarddata.setdata (' text ', Clipboarddata.getdata (' Text '). Replace (/[^\d]/g, ')) "

Use regular expression restrictions to enter only numbers and English:

Onkeyup= "Value=value.replace (/[\w]/g, ')" onbeforepaste= "Clipboarddata.setdata (' text ', Clipboarddata.getdata (' Text '). Replace (/[^\d]/g, ')) "

Match non-negative integers (positive integers + 0)

^\d+$

Match positive integers

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

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

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

Match negative integers

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

Match integer

^-?\d+$

Match non-negative floating-point number (positive floating point + 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 numbers

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

Matching floating-point numbers

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

Match a string consisting of 26 English letters

^[a-za-z]+$

Match a string consisting of 26 uppercase letters

^[a-z]+$

Match a string consisting of 26 letters in lowercase

^[a-z]+$

Match a string consisting of a number and 26 English letters

^[a-za-z0-9]+$

Matches a string consisting of a number, 26 letters, or underscores

^\w+$

Match email address

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

Match URL

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

Match HTML tag

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

Visual Basic & C # Regular Expression
1. Confirm valid e-mail format
The following example uses the static Regex.IsMatch method to verify whether a string is a valid e-mail format. If the string contains a valid e-mail address, the IsValidEmail method returns True, otherwise false, but no other action is taken. You can use IsValidEmail to filter out e-mail addresses that contain invalid characters before the application stores the address in the database or appears in an ASP.

[Visual Basic]

Function IsValidEmail (Strin as String) as Boolean
' 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}) (\]?) $")
End Function

[C #]

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}) (\]?) $");
}

2. Clean up the input string
The following code example uses the static Regex.Replace method to extract invalid characters from a string. You can use the CleanInput method defined here to erase potentially harmful characters entered in the Text field of a form that accepts user input. CleanInput returns a string after all non-alphanumeric characters except the @,-(hyphen), and. (period) are cleared.

[Visual Basic]

Function CleanInput (Strin As String) as String
' Replace invalid characters with empty strings.
Return Regex.Replace (Strin, "[^\w\[email protected]]", "" ")
End Function

[C #]

String CleanInput (String strin)
{
Replace invalid characters with empty strings.
Return Regex.Replace (Strin, @ "[^\w\[email protected]]", "" ");
}

3. Change the date format
The following code example uses the Regex.Replace method to replace the date form of the mm/dd/yy with the Dd-mm-yy date form.

[Visual Basic]

Function mdytodmy (input as String) as String
Return Regex.Replace (Input, _
"\b (<month>\d{)/(? <day>\d{})/(? <year>\d{2,4}) \b", _
"${Day}-${month}-${")
End Function

[C #]

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

Regex Replacement Mode
This example shows how to use a named reverse reference in the regex.replace substitution pattern. Where the substitution expression ${Day} Inserts a substring captured by the (?...) group.

There are several static functions that allow you to use regular expression operations without creating an explicit regular expression object, and the Regex.Replace function is one of them. If you do not want to keep the compiled regular expression, this will bring you convenience

4. Extracting URL Information
The following code example uses Match.result to extract the protocol and port number from a URL. For example, "http://www.penner.cn:8080 ... The "http:8080" will be returned.

[Visual Basic]

Function Extension (URL As String) as String
Dim R as New Regex ("^ (? <proto>\w+)://[^/]+?" (? <port>:\d+)?/", _
regexoptions.compiled)
Return r.match (URL). Result ("${Proto}${Port}")
End Function

[C #]

String Extension (string url)
{
Regex r = new Regex (@ "^ (? <proto>\w+)://[^/]+?" (? <port>:\d+)?/",
regexoptions.compiled);
return R.match (URL). Result ("${Proto}${Port}");
}

Regular expressions with only letters and numbers, not less than 6 digits, and numeric letters that contain passwords
In C #, you can use this to represent:

"\w{6} (\w+) *"

An algorithmic program that will need to split the path string into two parts of the root directory and subdirectory, taking into account the path format: C:\AA\BB\CC, \\AA\BB\CC, ftp://aa.bb/cc the above paths will be split into: \ C and AA\BB\CC, \\AA and \bb\ CC, ftp://and AA.BB/CC are implemented with JavaScript as follows:

var strroot,strsub
var regpathparse=/^ ([^\\^\/]+[\\\/]+|\\\\[^\\]+) (. *) $/
if (Regpathparse.test (strfolder))
{
Strroot=regexp.$1
Strsub=regexp.$2
}

Common 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.