Worthy Regular Expression (matching Chinese characters, matching double byte characters, matching HTML tags, matching empty lines and so on ~~~)

Source: Internet
Author: User

Keyword: Regular Expression Pattern Matching Javascript

Abstract: Common regular expressions are collected.

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. This post is updated at any time.

Regular Expression 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 for matching empty rows: \ n [\ s |] * \ r

Regular Expressions matching HTML tags:/<(. *)>. * <\/\ 1> | <(. *) \/>/

Regular Expression matching spaces at the beginning and end: (^ \ s *) | (\ s * $)

 

String. Prototype. Trim = function ()
{
Return this. Replace (/(^ \ s *) | (\ s * $)/g ,"");
}

Use regular expressions to break down and convert IP addresses:

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 +)/g // Regular Expression matching IP addresses
If (Re. Test (IP ))
{
Return Regexp. $1 * Math. Pow (255) + Regexp. $2 * Math. Pow () + Regexp. $3 * + 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 ))

The regular expression matching 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. For the reason, see the red font.]

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"
The result is incorrect. The result is: abeicfgg.
Limited capabilities of Regular Expressions

I used to post on csdn to seek an expression to remove repeated characters, but I couldn't find it. This is the simplest implementation method I can think. The idea is to use the back-to-back reference to retrieve repeated characters, then create a second expression with repeated characters, get non-repeated characters, and 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://www.9499.net/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 the full-width characters: onkeyup = "value = value. replace (/[^ \ uff00-\ Uffff]/g, '')" onbeforepaste = "clipboardData. setdata ('text', clipboardData. getdata ('text '). replace (/[^ \ uff00-\ Uffff]/g ,''))"

Use a regular expression to limit that only numbers can be entered: 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 ,''))"

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

 

 

 

 

/*** Calculate the string length and calculate the non-width characters as half characters ** @ Param Str * @ returns */function gblength (STR) {return typeof STR = "string "? Str. length + Str. replace (/[\ x00-\ x7f]/g ,''). length + 1> 1: 0;}/*** get the substring of the specified length of the string, calculate non-width characters as half characters ** @ Param Str * @ Param length * @ returns */function gbsubstr (STR, length) {If (typeof Str! = "String") return STR; Length + = length; For (VAR n = 0, L = Str. length; n <L & length> 0; n ++) {length-= Str. charcodeat (n)> 127? 2: 1;} return Str. substr (0, n);}/*** cut the specified length substring of the specified string. If the length exceeds the specified length, discard the last two characters and append the string... ** @ Param Str * @ Param Len * @ returns */function fit_length (STR, Len) {Len = Len | 16; If (typeof Str! = "String" | Str. length <= Len | gblength (STR) <= Len) {return STR;} var ret = gbsubstr (STR, len-2); return ret + '.. ';}

 

 

 

 

 

 

var replaceCJK = /[^\x00-\xff]/g,    testCJK    = /[^\x00-\xff]/;        cjkLength: function(strValue){            return strValue.replace(replaceCJK, "lv").length;        },        isCjk: function(strValue){            return testCJK.test(strValue);        },        cutString: function(str,len,suffix,slen){            suffix = suffix || '';            slen = slen || suffix.length;            if(str.length > len){                str = str.substr(0,len - slen) + suffix;            }            return str;        },        cutCjkString: function(str,len,suffix,slen){            suffix = suffix || '';            slen = slen || suffix.length;            len -= slen;            if(this.cjkLength(str) <= len){                return str;            }            var s = str.split(''),c = 0,tmpA = [];            for(var i=0;i<s.length;i+=1){                if(c < len){                    tmpA[tmpA.length] = s[i];                }                if(this.isCjk(s[i])){                    c += 2;                }else{                    c += 1;                }            }            return tmpA.join('') + suffix;        }    }

 

 

 

 

 

 

 

 

 

 

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.