Classic JavaScript regular expression [high quality typesetting]

Time:2020-10-24

Regular expression matching Chinese characters:

Copy codeThe code is as follows:
[\u4e00-\u9fa5]

Match double byte characters (including Chinese characters)

Copy codeThe code is as follows:
[^\x00-\xff]

Application: calculate the length of the string (a double byte character length meter 2, ASCII character count 1)

Copy codeThe code is as follows:
String.prototype.len=function(){ return this.replace([^\x00-\xff]/g,”aa”).length; }

Regular expression matching empty lines:

Copy codeThe code is as follows:
\n[\s|]*\r

Regular expression matching HTML tag:

Copy codeThe code is as follows:
/<(.*)>.*<\/\1>|<(.*) \/>/

Regular expressions that match leading and trailing spaces:

Copy codeThe code is as follows:
(^\s*)|(\s*$)

Application: there is no trim function like VBScript in J avascript. We can use this expression to implement it, as follows:

Copy codeThe code is as follows:
String.prototype.trim = function()
{
    return this.replace(/(^\s*)|(\s*$)/g, “”);
}

Using regular expression to decompose and transform IP address
The following is a JavaScript program that uses regular expressions to match IP addresses and converts IP addresses to corresponding values:

Copy codeThe code is as follows:
function IP2V(ip)
{
Re = / (- D +) \. [D +) \. (\ D +) \. (\ D +) / g / / regular expression matching 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 simpler to use split function to decompose directly. The program is as follows:

Copy codeThe code 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 matching email address:

Copy codeThe code is as follows:
\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

Regular expression matching URL of web address:

Copy codeThe code is as follows:
http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?

Using regular expressions to remove repeated characters in a string: [* Note: This program is not correct]

Copy codeThe code is as follows:
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

*Note
===============================
If var s = abacabefggeeii “
The result is wrong, the result is: abeiccfg
The power of regular expressions is limited
===============================

I originally posted an expression on CSDN to find an expression to remove duplicate characters, but I didn’t find it. This is the simplest method I can think of. The idea is to use the backward reference to extract the repeated characters, and then use the repeated characters to establish a second expression, get the non repeated characters, and connect the two. This method may not work for strings that require character order.

A JavaScript program that uses regular expressions to extract the file name from the URL address. The following result is page1

Copy codeThe code is as follows:
s=”http://blog.penner.cn/page1.htm”
s=s.replace(/(.*\/){ 0, }([^\.]+).*/ig,”$2″)
alert(s)

Using regular expressions to restrict the input content of text box in web form:

Use regular expression to restrict Chinese input only:

Copy codeThe code is as follows:
onkeyup=”value=value.replace(/[^\u4E00-\u9FA5]/g,”)” onbeforepaste=”clipboardData.setData(‘text’,clipboardData.getData(‘text’).replace(/[^\u4E00-\u9FA5]/g,”))”

Use regular expressions to restrict the input of full width characters only:

Copy codeThe code is as follows:
onkeyup=”value=value.replace(/[^\uFF00-\uFFFF]/g,”)” onbeforepaste=”clipboardData.setData(‘text’,clipboardData.getData(‘text’).replace(/[^\uFF00-\uFFFF]/g,”))”

Use regular expressions to restrict you to only enter numbers:

Copy codeThe code is as follows:
onkeyup=”value=value.replace(/[^\d]/g,”) “onbeforepaste=”clipboardData.setData(‘text’,clipboardData.getData(‘text’).replace(/[^\d]/g,”))”

Use regular expression to restrict the input of only numbers and English:

Copy codeThe code is as follows:
onkeyup=”value=value.replace(/[\W]/g,”) “onbeforepaste=”clipboardData.setData(‘text’,clipboardData.getData(‘text’).replace(/[^\d]/g,”))”

Match nonnegative integers (positive integers + 0)

Copy codeThe code is as follows:
^\d+$

Match positive integers

Copy codeThe code is as follows:
^[0-9]*[1-9][0-9]*$

Match non positive integers (negative integers + 0)

Copy codeThe code is as follows:
^((-\d+)|(0+))$

Match negative integers

Copy codeThe code is as follows:
^-[0-9]*[1-9][0-9]*$

Match integer

Copy codeThe code is as follows:
^-?\d+$

Match non negative floating point numbers (positive float + 0)

Copy codeThe code is as follows:
^\d+(\.\d+)?$

Match positive floating point numbers

Copy codeThe code is as follows:
^(([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 numbers (negative float + 0)

Copy codeThe code is as follows:
^((-\d+(\.\d+)?)|(0+(\.0+)?))$

Match negative floating point numbers

Copy codeThe code is as follows:
^(-(([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

Copy codeThe code is as follows:
^(-?\d+)(\.\d+)?$

Matches a string of 26 English letters

Copy codeThe code is as follows:
^[A-Za-z]+$

Matches a string of 26 uppercase letters

Copy codeThe code is as follows:
^[A-Z]+$

Matches a string of 26 lowercase letters

Copy codeThe code is as follows:
^[a-z]+$

Matches a string of numbers and 26 English letters

Copy codeThe code is as follows:
^[A-Za-z0-9]+$

Matches a string of numbers, 26 letters, or underscores

Copy codeThe code is as follows:
^\w+$

Match email address

Copy codeThe code is as follows:
^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$

Match URL

Copy codeThe code is as follows:
^[a-za-z] +: / / match (\ \ W + (- \ W +) *) (\. (\ \ W + (- \ W +) *) * (\ \ s *)$

Match HTML tag

Copy codeThe code is as follows:
<\s*(\S+)(\s[^>]*)?>(.*?)<\s*\/\1\s*>

Visual Basic & C# Regular Expression
1. Confirm valid email format
The following example uses static Regex.IsMatch Method to verify that a string is in a valid e-mail format. The isvalidmail method returns true if the string contains a valid e-mail address, false otherwise, but no other action is taken. You can use isvalidmail to store the address in the database or display it in the application ASP.NET Page to filter out email addresses that contain invalid characters.

[Visual Basic]

Copy codeThe code is as follows:
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#]

Copy codeThe code is as follows:
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 the input string
The following code example uses static Regex.Replace Method to extract invalid characters from a string. You can use the cleaninput method defined here to remove potentially harmful characters entered in the text fields of forms that accept user input. Cleaninput returns a string after removing all non alphanumeric characters except @, – (hyphen), and. (period).

[Visual Basic]

Copy codeThe code is as follows:
Function CleanInput(strIn As String) As String
‘ Replace invalid characters with empty strings.
Return Regex.Replace(strIn, “[^\w\[email protected]]”, “”)
End Function

[C#]

Copy codeThe code is as follows:
String CleanInput(string strIn)
{
    // Replace invalid characters with empty strings.
    return Regex.Replace(strIn, @”[^\w\[email protected]]”, “”);
}

3. Change date format
The following code example uses Regex.Replace Method to replace the date form of mm / DD / yy with the date form DD mm YY.

[Visual Basic]

Copy codeThe code is as follows:
Function MDYToDMY(input As String) As String
Return Regex.Replace(input, _
“\b(?<month>\d{ 1,2 })/(?<day>\d{ 1,2 })/(?<year>\d{ 2,4 })\b”, _
“${ day }-${ month }-${ year }”)
End Function

[C#]

Copy codeThe code is as follows:
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 }”);
}

Regex replacement mode
This example shows how to use the Regex.Replace The named reverse reference is used in the replacement pattern of. Where the replacement expression ${day} is inserted by (?) )The 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 Regex.Replace Function is one of them. If you don’t want to keep compiled regular expressions, this will be convenient for you

4. Extract URL information
The following code example uses Match.Result To extract the protocol and port number from the URL. For example“ http://www.penner.cn :8080…… Will return“ http:8080 ”。

[Visual Basic]

Copy codeThe code is as follows:
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#]

Copy codeThe code is as follows:
String Extension(String url)
{
    Regex r = new Regex(@”^(?<proto>\w+)://[^/]+?(?<port>:\d+)?/”,
    RegexOptions.Compiled);
    return r.Match(url).Result(“${ proto }${ port }”);
}

The regular expression of a password containing only letters and numbers, not less than 6 digits, and containing both numbers and letters
In C ා, this can be used to express:

Copy codeThe code is as follows:
“\w{ 6 }(\w+)*”

An algorithm program that splits the path string into two parts: root directory and subdirectory. Consider the path format as follows: C: ﹣ AA ﹣ BB ﹣ CC, \, ftp://aa.bb/cc The above paths will be split into: C: \, AA and AA / BB / cc, \ \ AA and / BB / cc, FTP: / / and aa.bb/cc It is implemented with JavaScript as follows:

Copy codeThe code is as follows:
var strRoot,strSub
var regPathParse=/^([^\\^\/]+[\\\/]+|\\\\[^\\]+)(.*)$/
if(regPathParse.test(strFolder))
{
    strRoot=RegExp.$1
    strSub=RegExp.$2
}