Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the regular expressions commonly used in JavaScript

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article will explain in detail what regular expressions are commonly used in JavaScript. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

/ / check whether it is made up of numbers.

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

Regular expression that matches Chinese characters: [u4e00-u9fa5]

Note: matching Chinese is really a headache. It's easy to have this expression.

Match double-byte characters (including Chinese characters): [^ x00-xff]

Note: can be used to calculate the length of a string (a double-byte character length meter 2 ~ ~ ASCII character counter 1)

A regular expression that matches a blank line: ns*r

Comment: can be used to delete blank lines

A regular expression that matches the HTML tag:

< (S*?)[^>

] * >. *? |

< .*? />

Commentary: the version circulated on the Internet is too bad, the above one can only match part of it, and there is still nothing I can do about complex nested tags.

Regular expression that matches the leading and trailing white space characters: ^ s* | slots $

Comment: a very useful expression that can be used to delete white space characters (including spaces, tabs, page feeds, etc.) at the beginning and end of a line

Regular expression that matches the Email address: W + ([- +.] w +) * @ w + ([-.] w +) * .w + ([-.] w +) *

Comment: form validation is very useful

Regular expression that matches the URL URL: [a-zA-z] +: / / [^ s] *

Note: the function of the version circulated on the Internet is very limited, and the above version can basically meet the needs.

Whether the matching account is legal (5-16 bytes are allowed at the beginning of the letter, and alphanumeric underscores are allowed): ^ [a-zA-Z] [a-zA-Z0-9 _] {4j 15} $

Comment: form validation is very useful

Match domestic phone number: d {3}-d {8} | d {4}-d {7}

Commentary: matching forms such as 0511-4405222 or 021-87888822

Match Tencent QQ number: [1-9] [0-9] {4,}

Commentary: Tencent QQ starts from 10000

Match the postcode of China: [1-9] d {5} (?! d)

Commentary: the postal code of China is 6 digits

Match ID: d {15} | d {18}

Commentary: Chinese ID cards are 15 or 18 digits

Match the ip address: dong.dharm.ding.d+

Note: useful when extracting ip addresses

Match specific numbers:

^ [1-9] $/ / match positive integers

^-[1-9] $/ / match negative integers

^ -? [1-9] d _ match $/ / match integer

^ [1-9] d * | 0 $/ / matches a non-negative integer (positive integer + 0)

^-[1-9] d * | 0 $/ / matches non-positive integers (negative integers + 0)

^ [1-9] dquo.d* | 0.d* [1-9] droom$ / / matches positive floating point numbers

^-([1-9] dfol.d* | 0.d* [1-9] d*) $/ / matches negative floating point numbers

^ -? ([1-9] droom.d* | 0.d* [1-9] d* | 0room.0+ | 0) $/ / match floating point number

^ [1-9] dfol.d* | 0.d* [1-9] d* | 0room.0+ | 0 $/ / match non-negative floating point number (positive floating point number + 0)

^ (- ([1-9] dfu.d* | 0.d* [1-9] d*)) | 0room.0+ | 0 $/ / matches non-positive floating point numbers (negative floating point numbers + 0)

Commentary: useful when dealing with a large amount of data, pay attention to corrections in specific applications

Match a specific string:

^ [A-Za-z] + $/ / matches a string of 26 English letters

^ [Amurz] + $/ / matches a string of 26 English letters in uppercase

^ [amurz] + $/ / matches a string of 26 lowercase letters

^ [A-Za-z0-9] + $/ / matches a string of numbers and 26 letters

^ wrist $/ / matches a string consisting of numbers, 26 letters, or underscores

The validation features and their validation expressions when using RegularExpressionValidator validation controls are described as follows:

You can only enter a number: "^ [0-9] * $"

Only n-digit numbers can be entered: "^ d {n} $"

You can only enter at least n digits: "^ d {n,} $"

You can only enter the number of mmurn digits: "^ d {mdirection n} $"

You can only enter zero and non-zero numbers: "^ (0 | [1-9] [0-9] *) $"

You can only enter positive real numbers with two decimal places: "^ [0-9] + (. [0-9] {2})? $"

You can only enter positive real numbers with 1-3 decimal places: "^ [0-9] + (. [0-9] {1pr 3})? $"

You can only enter a positive integer that is not zero: "^ +? [1-9] [0-9] * $"

You can only enter a negative integer that is not zero: "^-[1-9] [0-9] * $"

Only characters of length 3 can be entered: "^. {3} $"

You can only enter a string of 26 letters: "^ [A-Za-z] + $"

You can only enter a string of 26 capital letters: "^ [Amurz] + $"

You can only enter a string of 26 lowercase letters: "^ [amurz] + $"

You can only enter a string of numbers and 26 letters: "^ [A-Za-z0-9] + $"

You can only enter a string consisting of numbers, 26 letters, or an underscore: "^ wicked $"

Verify the user password: "^ [a-zA-Z] w {5pm 17} $" is in the correct format: begins with a letter and is between 6 and 18 in length

Can only contain characters, numbers, and underscores.

Verify whether it contains characters such as ^% &',; =? $":" [^% &',; =? $x22] + "

You can only enter Chinese characters: "^ [u4e00-u9fa5], {0,} $"

Verify the Email address: "^ w + [- +.] w +) * @ w + ([-.] w +) * .w + ([-.] w +) * $"

Verify InternetURL: "^ http://([w-]+.)+[w-]+(/[w-./?%&=]*)?$"

Verify the phone number: "^ ((d {3pr 4}) | d {3pr 4} -)? d {7pr 8} $"

The correct format is "XXXX-XXXXXXX", "XXXX-XXXXXXXX", "XXX-XXXXXXX"

"XXX-XXXXXXXX", "XXXXXXX", "XXXXXXXX".

Verify ID number (15 or 18 digits): "^ d {15} | d {} 18 $"

Verify the 12 months of the year: "^ (0? [1-9] | 1 [0-2]) $" the correct format is: "01"-"09" and "1"12"

Verify 31 days of a month: "^ ((0? [1-9]) | (1 | 2) [0-9]) | 30 | 31) $"

The correct formats are "01", "09" and "1"31".

Regular expression that matches Chinese characters: [u4e00-u9fa5]

Match double-byte characters (including Chinese characters): [^ x00-xff]

Regular expression that matches blank lines: n [s |] * r

Regular expression that matches the HTML tag: /

< (.*)>

. * |

< (.*) />

/

Regular expression that matches leading and trailing spaces: (^ s*) | (sworn $)

Regular expression that matches the Email address: W + ([- +.] w +) * @ w + ([-.] w +) * .w + ([-.] w +) *

The regular expression that matches the URL URL: http://([w-]+.)+[w-]+(/[w-. /?% & =] *?

(1) Application: calculate the length of a string (a double-byte character length meter 2 ~ ~ ASCII character counter 1)

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

(2) Application: if there is no trim function like vbscript in javascript, we can use this expression to implement

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

(3) Application: using regular expressions to decompose and translate IP addresses

Function IP2V (ip) / / IP address is translated into the corresponding value {re=/ (d +). (d +). (d +) / g / / the regular expression if (re.test (ip)) {return RegExp.$1*Math.pow (255prime2)) + RegExp.$2*Math.pow (255prime2) + RegExp.$3*255+RegExp.$4*1} else {throw new Error ("Not a valid IP address!")}}

(4) Application: javascript program that extracts file names from URL addresses

S = "http://www.9499.net/page1.htm";s=s.replace(/(.*/){0,}([^.]+).*/ig,"$2"); / / Page1.htm

(5) Application: use regular expressions to restrict the input of text boxes in web forms.

Use regular expressions to limit input to Chinese: onkeyup= "value=" / blog/value.replace (/ ["^ u4E00-u9FA5] / g,") "

Onbeforepaste= "clipboardData.setData ('text',clipboardData.getData (' text'). Replace (/ [^ u4E00-u9FA5] / g,") "

Use regular expressions to restrict input to full-width characters: onkeyup=value= "/ blog/value.replace (/ [" ^ uF00-uFFFF] / g, ")"

Onbeforepaste= "clipboardData.setData ('text',clipboardData.getData (' text'). Replace (/ [^ uFF00-uFFFF] / g,") "

Use regular expressions to restrict input to numbers: onkeyup= "value=" / blog/value.replace (/ [^ d] / g, ")" onbeforepaste= "clipboardData.setData

('text',clipboardData.getData (' text') .replace (/ [^ d] / g, ")"

Use regular expressions to limit input to numbers and English: onkeyup= "value=" / blog/value.replace (/ [W] / g, ")" onbeforepaste= "clipboardData.setData

('text',clipboardData.getData (' text'). Replace (/ [^ d] / g,)

Regular expressions in, js removes html tags, removes characters, truncates characters (2009-01-11 10:20:14)

2007-07-08 15:26

1. Get the link address on the web page:

String matchString = @ "] + href=\ s * (?:'(? [^'] +)'|" (? [^ ""] +) "| (? [^ >\ s] +))\ s* [^ >] * >"

2. Get the title of the page:

String matchString = @ "(?. *)"

3. Remove all html tags from the page:

String temp = Regex.Replace (html, "] * >", "); / / html is a document to remove the html tag

Remove all tags from a web page in java

Str = str.replaceAll ("] * >", "")

4, string matchString = @ "([\ S\ s\ t] *?)"

5JS remove all the functions marked by html:

Function delHtmlTag (str) {return str.replace (/ / g, ""); / / remove all html tags}

This IE5 may be wrong, then use this, plum blossom:

Function delHtmlTag (str) {return str.replace (/] + > / g, ""); / / remove all html tags}

Check login name: you can only enter 5-20 characters that begin with a letter, can be numbered, "_", "." String of

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

Source: regular matching space problem

The character keys in the string have spaces, but the number of spaces may be inconsistent, so the number of spaces is unified into one by regularization.

For example: blue idea

Become: blue idea

The regularity of aobert:

Var str= "Blue idea" var reg=/\ s ideal str= str.replace g str= str.replace (reg, ") [xss_clean] (str)

Determine whether a string is made up of numbers

Source: is there an easy way to determine that a string is made up of numbers?

This rule is relatively simple. I wrote a test.

Function isDigit (str) {var reg = / ^\ dbadge; return reg.test (str);} var str = "7654321"; [xss_clean] (isDigit (str)); var str = "test"; [xss_clean] (isDigit (str))

Telephone number regularization

Source: I'd like to ask about the regular judgment of phone numbers.

Find a JS rule that verifies the phone number

/ ^\ d {3pr 4} -\ d {7jue 8} (-\ d {3pr 4})? the $/ area code must be a number of 3-4 digits, followed by the area code to connect with the phone number with "-"

^\ d {3pm 4}-the phone number is a number of 7-8 digits

\ d {7prit 8} the extension number is a number of 3-4 digits, which is not required, but if filled in, it is connected to the phone number with "-".

(-\ d {3jue 4})? Regular expression of mobile phone number

Regular verification of mobile phone number, ignoring the previous 0, support 130,139150-159. It is judged to be 11-bit after ignoring the previous 0.

The regularity of cloeft:

/ ^ 0* (13 | 15)\ d {9} $/ ^ 0* matches any number of zeros at the beginning.

Since the mobile phone number is 13 arbitrary digits 9 digits, and 15 arbitrary digits 9 digits, it can be matched with (13 | 15)\ d {9}.

The test code is as follows:

Function testReg (reg,str) {return reg.test (str);} var reg = / ^ 0* (13 | 15)\ d {9} $/; var str = '13889294433; var str2 =' 12889293333; var str3 = '23445567); [xss_clean] (testReg (reg,str) +'); [xss_clean] (testReg (reg,str2) +'); [xss_clean] (testReg (reg,str3) +')

Use regular expressions to remove spaces in a string:

Source: is there any function in js that removes spaces?

The code and the test code are as follows:

/ / removes white space characters on both sides of the string. Function trim (str) {return str.replace (/ ^\ s + |\ swords / delete the white space character on the left side of the string. Function ltrim (str) {return str.replace (/ ^\ sdelete the white space character on the right side of the string. The function rtrim (str) {return str.replace (/\ smatching plumbabash gpencil'); the following is the test code var trimTest = "123456789"; / / there is a space before and after each space. [xss_clean] ('length:'+trimTest.length+''); / / before using [xss_clean] (' ltrim length:'+ltrim (trimTest) .length +'); / / after using ltrim [xss_clean] ('rtrim length:'+rtrim (trimTest) .length +'); / / after using rtrim [xss_clean] ('trim length:'+trim (trimTest) .length +'); / / after using trim

The test results are as follows:

Length:11

Ltrim length:10

Rtrim length:10

Trim length:9 restricts text boxes to enter only numbers, decimal points, etc.

Source: the problem of text box input restrictions?

You can only enter numbers and decimal points

Var reg = / ^\ d *\.?\ d {0jin2} $/ begins with a number of numbers, with 0 or a decimal point in the middle, and ends with 0 to 2 digits.

You can only enter lowercase letters and decimal points, colons, forward and backward slashes (:. /\)

Var reg = / [a murz\.\ /\:] + /; a murz includes lowercase letters,\. It's the decimal point,\ / and\\ are the left and right backslashes, respectively, and finally the colon. The whole composition of a character set and code can be any one, and finally add +, 1 or more.

Replace the content before the decimal point to the specified content

Source: find a regular expression!

Could you tell me how to replace the character before the decimal point of this string with my custom string?

For example, replace infomarket.php?id=197 with test.php?id=197

It should be possible to turn the first point. Just replace all the previous word characters with test. The rules I wrote are as follows:

Var str = "infomarket.php?id=197"; var reg = / ^\ wishtag; / / matches any word character at the beginning of the string str = str.replace (reg,'test'); [xss_clean] (str)

The original post was a little complicated and didn't read it very well.

Only match regular expressions in Chinese

Source: when uploading, you can only choose pictures with Chinese names (can you use the toASCII method? )

The "JavaScript developer King" I saw two days ago happens to have a Chinese unicode scope, and the rules are as follows:

/ [\ u4E00 -\ u9FA5\ uf900-\ ufa2d] / wrote a simple test that will replace all Chinese with "Oh".

Var str = "Chinese? and English."; var reg = / [\ u4E00 -\ u9FA5\ uf900-\ ufa2d] / ig; str = str.replace (reg,''); [xss_clean] (str)

Returns the number of Chinese characters in a string

Source: is there a function that returns Chinese character bytes?

The general character length is the same for Chinese and English, such as length in JS, so how to return the number of Chinese characters in the string? Teacher guoshuang gave the solution in the original post, but I didn't understand it.

But I have an idea myself: first remove the non-Chinese characters, and then return the length attribute. The function and test code are as follows:

Function cLength (str) {var reg = / [^\ u4E00 -\ u9FA5\ uf900-\ ufa2d] / g; / / matches the non-Chinese regular expression var temp = str.replace (reg,''); return temp.length;} var str = "Chinese 123"; [xss_clean] (str.length+''); [xss_clean] (cLength (str))

Results:

five

two

Two in Chinese, three in numbers, correct.

The following tests are also correct.

Var str = "123 tesses written in Chinese% str # [] [{}"; [xss_clean] (str.length+''); [xss_clean] (cLength (str))

The regular expression obtains the first three segments of the matching IP address

Source: how to use regularization to fetch the first 3 segments of IP

192.168.118.101192.168.118.72, 192.168.118.1 were replaced by: 192.168.118

Just match the last paragraph and replace it with an empty string, the rule is as follows:

/\.\ d {1J 3} $/ matches the .n, .nn or .nnn at the end.

The test code is as follows:

Function replaceReg (reg,str) {return str.replace (reg,'')} var reg = /\.\ d {1Magne3} $/; var str = '192.168.118.101; var str2 =' 192.168.118.72; var str3 = '192.168.118.118.1; [xss_clean] (replaceReg (reg,str) +'); [xss_clean] (replaceReg (reg,str2) +'); [xss_clean] (replaceReg (reg,str3) +')

Similarly, there is a way to verify the IP address in this post: to verify the regular expression of the MAC address.

Match the content between and

Source: please ask me a regular question.

Safsfsafsfsafsf

With regularity, you can get the content between the next and the next.

The rules are as follows:

/ [\ s\ S] +? / I first matches the ul tags on both sides, and the middle [\ s\ S] +? Can match one or more arbitrary characters, must not be greedy, otherwise it will match safsfsafsf.

Get the file name with a regular expression

Source: C:\ 006.jpg

C:\ images\ tupian\ 006.jpg

It may be directly under the root of the drive letter, or in several layers of directory, it may be required to be replaced to only the file name.

The regularization of xlez is as follows:

/ [^\] + / g first matches 0 or more non-left and right slash characters, followed by one or more left and right slashes. Shaped like "xxx/" or "xxx\" or "/" or "\"

Function and test code:

Function getFileName (str) {var reg = / [^\\ /] * [\\ /] + / g; / / xxx\ or xxx/ str = str.replace (reg,''); return str;} var str = "c:\\ images\\ tupian\\ 006.jpg"; [xss_clean] (getFileName (str) +'); var str2 = "c:/images/tupian/test2.jpg"; [xss_clean] (getFileName (str2))

Note that\ needs to be escaped.

Absolute path to relative path

Source: discuss a rule

Set

Convert to:

.

The URL may change, such as http://localhost and so on.

The regularity of cloudchen:

/ http:\ /\ / [^\ /] + / first http://, and then [^\ /] + looked for one or more non / characters, because the first / indicates that you have reached the directory, stop matching.

The test code is as follows:

Var str ='

'; var reg = / http:\ /\ / [^\ /] + /; str = str.replace (reg, "); alert (str)

User name regularization

Source: seek regularity, hurry!

For user name registration, the user name can only be in Chinese, English, numbers, underscores, 4-16 characters.

Regularize hansir and solutions:

/ ^ [\ u4E00 -\ u9FA5\ uf900-\ ufa2d\ w] {4pm 16} $/ Chinese characters or word characters, 4 to 16. The key to achieving 4 to 16 knots into the regular is the start ^ and the end $, which means that the whole string can only have these matches, not extra.

The function and test code are as follows:

Function isEmail (str) {var reg = / ^ [\ u4E00 -\ u9FA5\ uf900-\ ufa2d\ w] {4pm 16} $/; return reg.test (str);} var str = 'super invincible username regExp'; var str2 =' disruptive @'; var str3 = 'too short' var str4 = 'too long longlonglonglonglonglonglonglong' [xss_clean] (isEmail (str) +'); [xss_clean] (isEmail (str2) +'); [xss_clean] (isEmail (str3) +') [xss_clean] (isEmail (str4) +'')

Match English address

Source:-ask for help-regular question

The rules are as follows:

Contains "dot", "letter", "space", "comma", "number", but the beginning and end cannot be any character except letters.

This character set implements letters, spaces, commas and numbers. [\ .a-zA-Z\ s] The final rule is as follows:

/ ^ [a-zA-Z] [\ .a-zA-Z\ s zA-Z 0-9] *? [a-zA-Z] + $/ must begin with a letter and end with more than one letter. The test code is as follows:

Function testReg (reg,str) {return reg.test (str);} var reg = / ^ [a-zA-Z] [\ .a-zA-Z\ s No.8,ChangAn Street,BeiJing,China88' 0-9] *? [a-zA-Z] + $/; var str = 'No.8,ChangAn Street,BeiJing,China'; var str2 =' 8. [xss_clean] (testReg (reg,str) +') [xss_clean] (testReg (reg,str2) +') [xss_clean] (testReg (reg,str3) +'')

Regular matching price

Source: why doesn't this rule work? In a hurry?

The format of the price should be as follows:

The first number of digits, there may be a decimal point, and there can be two digits after the decimal point. The corresponding rules given by hansir are as follows:

/ ^ (\ d *\.\ d {0jin2} |\ d +). The test code given by $/ hansir is as follows:

The untitled document function checkPrice (me) {if (!) (/ ^ (?:\ d+ |\ d+\.\ d {0Magne2}) $/ .test (me.value)) {me.value = me.value.replace (/ ^ (\ d*\.\ d {0Magne2} |\ d+). * $/,'$1');}}, and the href attribute can be one or more characters other than line breaks (not greedy). Followed by. +?, one or more characters other than line breaks (not greedy), followed by a closing tag.

There is a problem, if the opening tag of a has a space at the end, or if there are other attributes besides href, the above regular will not match the link.

For example:

…… There's an extra space.

To save here, only the text content of the link is saved and the tag information is deleted.

A regular matching link was written earlier:

/ [\ s\ S] *? / but what we need to capture is the text content, so we need to make some changes. The first step is to add "?" in all parentheses to indicate no capture. The second step is to add one more parenthesis and put it in [\ s] *? On both sides, so that the text content of the link can be captured. The final rule is as follows:

/ ([\ s\ S] *?) /

The test code is as follows:

Function anchorText (str) {var reg = / ([\ s\ S] *?) /; str = str.replace (reg,'$1'); return str;} var str = 'Classic Forum'; [xss_clean] (anchorText (str))

Regularization determines whether the label is closed or not

Source: it is very difficult to ask for help! How to determine whether a label is closed by a regular expression

For example:

[\ s\ S] *?)

Matches the closing tag of the\ p class tag. > is actually at the end of the tag, followed by several arbitrary characters of the tag content, and finally the end of the tag.

Add one or you can solve the final complete regular expression:

The whole rule:

/ [\ s\ S] *? |\ s*\ / >) / I take this regular, as long as it matches, it means closed, and if it doesn't match, it doesn't close. However, the nesting of the same tags is not considered, such as

Aaaaaatest

It is also judged to be qualified by writing the final matching p-class end tag as a sub-regular expression and changing it to non-greedy, and then check whether it is paired in the matching result. The rules are as follows:

/ [\ s\ S] *? () + |\ s*\ / >) / I get the content of the specified tag with the rule

Source: seek a rule

The code is as follows:

Blue ideal Interface Design Test Specification "Classical realistic Beauty" Cartoon course Anyuan-- vanishing Lightyear asp.net 2.0 multilingual website solution

It is required to match the title in item rather than the title in channel.

Basic regularity:

/ [\ s\ S] *? / gi is first the title tag with several arbitrary characters, followed by the title closing tag. This regular already matches all the title tags.

First of all, I simply modified the original rule:

/ [^] *? / gi, because there should be no other tags embedded in the title, this rule also matches the content of all headings, plus not matching the title in the channel. The whole rule is as follows:

/ [^] *? (?!\ s*) / gi (?!\ s*) indicates that the string cannot be followed by several spaces and the closing tag of a channel.

There are convenient testing tools in the original post, so there is no test code here.

Regular judgment whether it is a mixture of numbers and letters

Source: about regularities

Cannot be less than 12 digits and must be a mixture of letters and numbers.

The verification string contains numbers, the verification string contains letters, and the verification string does not contain other characters. You can use these three regularities to check the string once and logically calculate the final result.

But how can these functions be written into a regular expression? This question is really nerve-racking.

Here are the rules for lexrus:

/ ^ ([a murz] + (? = [0-9]) | [0-9] + (? = [a murz])) [a-z0-9] + $/ ig is very clear:

[a murz] + (? = [0-9])

The letter begins and must be followed by a number.

[0-9] + (? = [amurz]

The number begins and must be followed by letters.

[a-z0-9] +

As long as the following characters are numbers or letters. After testing, it is found that it does not work, 123dd will be identified as illegal, dd123 is legal, it can be seen that the "number begins, followed by letters" rule does not work. The test code is as follows:

Function istrue (str) {var reg=/ ^ ([Amurz] + (? = [0-9]) | [0-9] + (? = [Amurz])) [a-z0-9] + $/ ig; return reg.test (str);} var str? = 'AaBc'; var str2 =' aaa123'; var str3 = '123ddbath; var str4 =' 1230923403982); [xss_clean] (istrue (str) +'); [xss_clean] (istrue (str2) +') [xss_clean] (istrue (str3) +'); [xss_clean] (istrue (str4) +'')

The result is:

False,true,false,false

The third of the results is that it is wrong to judge '123dd' as illegal. At first I thought it was the problem of g, but it didn't work if I got rid of it. It should be the browser bug. I think the regularity of lexrus is correct. It may be that the browser cannot handle it or that both sides of the "|" contain forward preview (? =).

The revised rule is as follows:

/ ^ (([a murz] + [0-9] +) | ([0-9] + [a murz] +)) [a-z0-9] * $/ I

The meaning is similar to the above, but forward prechecking is not used. The test code is as follows:

Function istrue (str) {var reg=/ ^ (([Amurz] + [0-9] +) | ([0-9] + [AMurz] +)) [a-z0-9] * $/ I; return reg.test (str);} var str? = 'AaBc'; var str2 =' aaa123'; var str3 = '123ddbath; var str4 =' 1230923403982; [xss_clean] (istrue (str) +'); [xss_clean] (istrue (str2) +') [xss_clean] (istrue (str3) +'); [xss_clean] (istrue (str4) +'')

The result is

False,true,true,false

That's right.

Spaces and English exist at the same time.

Source: please give me some advice on regular questions.

To match English and spaces, both letters and spaces are required.

This idea is similar to the above, as long as the number is changed into a space. The rules are as follows:

/ ^ (([amethz] +\ s +) | (\ s + [a-z] +)) [amurz\ s] * $/ I begins with a space, or a space is added at the beginning of the space, followed by English or space. The test code is as follows:

Function istrue (str) {var reg=/ ^ (([Amurz] +\ s +) | (\ s + [a-z] +)) [aMurz\ s] * $/ I; return reg.test (str);} var str? = 'asdf'; var str2 =' sadf sdf'; var str3 = 'asdf'; [xss_clean] (istrue (str) +'); [xss_clean] (istrue (str2) +'); [xss_clean] (istrue (str3) +')

Using this idea, we can also achieve the matching of English blanks and more than two English words. Similarly, you can replace English letters with word characters\ w.

Show or save part of the regular expression match

The telephone number is as follows:

13588888333

13658447322

13558885354

13587774654

13854554786

Only phones starting with 135 are required to be matched, but only the numbers after 135 are retained in the matching result.

Since regularities in JavaScript do not support (? = xx) xxx mode, only xxx (? = xx) mode is supported. So you can only match the content after 135 as a sub-regular expression, and then reference it later.

The functions given by Carl are as follows:

Function f (phoneNumber) {var pattern = / ^ (135) (\ d {8}) $/; if (pattern.test (phoneNumber)) return phoneNumber.replace (pattern, "$2"); else return "is not a mobile number starting with 135!" ;}

In / ^ (135C) (\ d {8}) $/ regular, 135represents the first sub-regular expression as the beginning, and the second parenthesized sub-regular expression matches the next eight digits, and then uses $2 in replace to refer to what this sub-regular expression matches. The test code is as follows:

Function f (phoneNumber) {var pattern = / ^ (135) (\ d {8}) $/; if (pattern.test (phoneNumber)) return phoneNumber.replace (pattern, "$2"); else return "is not a mobile number starting with 135!" ;} var arr = new Array ("13588888333", "13658447322", "13558885354", "13587774654", "13854554786"); for (var I = 0; I

< arr.length; i++) [xss_clean](f(arr[i])+''); 正则表达式替换变量 来源:求教正则 有一个数组: var _A = ['A','B','C','D']; 有一个有"变量"的字符串。 var _B = '$0$$1$$2$$3$'; 说是变量,其实只是字符串中的特殊字符,例如$0$,就称这个为伪变量吧。 最后的要求就是使用正则获得下面这样一个字符串: _C = 'ABCD'; IamUE给出了代码: var _A = ['A','B','C','D']; var _B = '$0$$1$$2$$3$'; var reg=/\$\d+\$/ig; C=_B.replace(reg,function($1){ var indexnum=$1.replace(/\$/ig,""); if (indexnum结束。 测试代码如下: function replaceReg(reg,str){ return str.replace(reg,'[img]$1[/img]') } var reg = //ig; var str = '我就是传说中的图片了

Hey.' ; [xss_clean] (replaceReg (reg,str) +'')

The second is to replace the object code embedded in flash code with

Flash animation

Play online

.

The rules for the original text are as follows:

/\ "\ s] + match property values. Mismatch >" and spaces. The quotation marks here need not be escaped. Without changing the meaning, it has been changed slightly, and the rules are as follows:

/ (\ s +\ w +) = ([^ > "\ s] +) / ig needs to note that this regular mismatch = an attribute with spaces on both sides, such as href = xxx. If it matches, change it to:

/ (\ s +\ w +)\ scodes =\ s * ([^ > "\ s] +) / ig code:

Str=str.replace (/ (?!\ "\"\ s] +) / ig,'$1= "$2"); where'$1 = "$2" realizes adding double quotation marks to the attribute value. However, ncs points out several problems with this regular substitution, one is the space problem above, and the other is that if there is an equal sign inside the non-tag and happens to be preceded by a white space character, it will be mistakenly recognized as an attribute, such as:

Test=sd

The test=sd inside will also be matched. Third, if the attribute originally uses single quotation marks, it will be wrapped in double quotation marks.

Let's take a look at the new regular replacement method of LeXRus's predecessors:

Str=str.replace (/ (?!\ "\ s] +) (? = [^ >] * >) / ig,'$1=" $2 "). Replace (/\" ([^\ "] +)\" / ig,'\ "$1\")

Let's take a look at the first rule:

/ (\ s +\ w +)\ swords =\ s * ([^ > "\ s] +) (? = [^ >] * >) / new addition at the end of ig (? = [^ >] * >) is intended to solve the problem that the equal sign is mistakenly identified as an attribute in ordinary text:

Test=sd

There's no problem, but...

Another tag for test=sd

The test=sd in the is recognized as an attribute.

I think it's okay to change it to the following rules:

/ (\ s +\ w +)\ ig =\ s * ([^ "\ s] +) (? = [^] * >) / ig adds one to the second parenthesis character set and the last reverse pre-checked character set) / ig var reg2 = /" ([^'"] *)'" / ig; str=str.replace (reg1,'$1= "$2"') .replace (reg2,'\ "$1\"); } asfd=asfd) / ig is to remove the characters in the second parenthesis set. Finally, this problem is also solved.

Add tbody to table

Source: quickly add after through regular expressions

There are several table, but no tbody. Now you need to add it in regular batches.

It's easy to match the table closing tag, just add one in front of it.

However, it is a bit difficult to match the starting tag of the table because there may be attributes. But the links have been matched before, and this is more or less the same.

The table code of the instance is as follows:

Regular:

A match of / / g indicates the end of the tag.

Then replace it and add it.

Remove all attributes of the tag

Source: regular expression (Dreamweaver8)

***

Become something without any attributes.

***

Idea: non-capture matching attributes, capture matching tags, and replace strings with capture results. The rules are as follows:

/ () / first, the td matches the tag, which can be referenced later with $1, the following attributes are matched by (?:), and the final matching > can be referenced later with $2.

Cosmetic code:

Str = str.replace (reg,'$1 $2')

Regular replacement of specific words

Source: regular expression, how to reject the input of a few words?

Require that certain words are prohibited, if red,yellow,white is rejected. This post will not be difficult, but it has made me clear on several concepts.

First, be careful of the "OR" in the character set

/ [^ red | yellow | white] / all or in this rule is meaningless and is equivalent to:

/ [^ redyellowwhite] / means that it cannot contain all the letters listed below.

Positive solution:

/ red | yellow | second concept of white/:

As long as the entire regular match succeeds, the parentheses are captured regardless of whether the sub-regular expression matches successfully or not. For example

/ (red) | (yellow) | (white) / will capture three results, although in fact, at most one parenthesis match is possible. But as long as one matches, the other two will also record the empty string.

Specify text highlight

Source: how to highlight specified words in a web page with rules

Ask regular expressions: how to replace keywords in search results with highlights?

Get something for nothing, this non-existent predecessor has given a very good solution: I posted the code directly:

Function encode (s) {return s.replace (/ & / g, "&"). Replace (/ / g, ">"). Replace (/ ([\\.\ *\ [\]\]\ (\)\ $\]) / g, "\ $1");} function decode (s) {return s.replace (/ /\ ([\\.\ *\]\ (\)\ $\]) / g, "$1") .replace (/ > / g, ">") .replace (/)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report