Special characters in regular expressions
Character implication
\ As a turn, that is, the characters usually after "\" are not interpreted in the original sense, such as the/b/matching character "B", when B is preceded by a backslash/\b/, to match the boundary of a word.
-or-
a restore of a regular expression feature character, such as "*" that matches its preceding metacharacters 0 or more times,/a*/will match a,aa,aaa, and after "\",/a\*/will only match "a *". The
^ matches an input or the beginning of a line./^a/matches "an A", but does not match "an A"
$ matches an input or end of a line,/a$/matches "an A" and does not match "an A"
* matches the preceding metacharacters 0 or more times,/ba*/will match B, BA,BAA,BAAA
+ matches the preceding metacharacters 1 or more times,/ba*/matches ba,baa,baaa
? Matches the preceding metacharacters 0 or 1 times,/ba*/matches the B,ba
(x) match x saves x in the variable named $1...$9
X |y matches x or y
{n} exact match n times
{n,} matches n more than
{n,m} matching n-m times
[XYZ] Character set (character set), matching any one by one characters (or metacharacters) in this collection
[^xyz] does not match this Any one of the characters in the collection
[\b] matches a backspace
\b The bounds of a word
\b match the non-boundary of a word
\cx here, X is a control character,/\cm/match ctrl-m
\d match a character number character,/\d/=/[ 0-9]/
\d matches a non-numeric character,/\d/=/[^0-9]/
\ n matches a newline character
\ r matches a carriage return
\s matches a blank character, including \n,\r,\f,\t,\v, and so on
\s matches a non-white-space character, equal to /[^\n\f\r\t\v]/
\ t matches a tab character
\v matches a heavy-tab
\w match one of the characters that can make up a word (alphanumeric, this is my transliteration, with numbers), including underscores, such as [\w] Match "$5.98" 5 equals [a-za-z0-9]
\w matches a character that cannot be made into words, such as [\w] matches $ in "$5.98", equal to [^a-za-z0-9].
It is better to use re = new RegExp ("pattern", ["flags"]) Pattern: Regular Expressions Flags:g (all occurrences of pattern in Full-text lookup) I (Ignore case) m (Multiple-line lookup) |
The problem of vascript dynamic regular expression Can the regular expression be generated dynamically? For example, in javascript: var str = "strtemp"; To build: var re =/strtemp/; If it is a character connection: var re = "/" + str + "/" Can But to generate an expression, can you implement it? |
|
A regular expression is an object that describes a character pattern.
JavaScript's RegExp objects and string objects define methods that use regular expressions to perform powerful pattern matching and text retrieval and substitution functions.
In JavaScript, a regular expression is represented by a RegExp object. Of course, you can use a regexp () constructor to create the RegExp object.
You can also create a RegExp object by using a new special syntax that is added in JavaScript 1.2. Just as a string literal is defined as a character enclosed in quotation marks,
The direct amount of a regular expression is also defined as a character that is contained between a pair of slashes (/). Therefore, JavaScript may contain the following code:
var pattern =/s$/;
This line of code creates a new RegExp object and assigns it to the variable parttern. This particular RegExp object matches all strings that end with the letter "s". You can also define the
An equivalent regular expression with the following code:
var pattern = new RegExp ("s$");
It is easy to create a RegExp object whether using a regular expression or a constructor regexp (). The more difficult task is to use regular expression syntax to describe the pattern of characters.
JavaScript uses a fairly complete subset of the regular expression syntax in Perl.
The pattern specification for regular expressions is made up of a series of characters. Most characters, including all alphanumeric characters, describe characters that are matched literally. In this case, the regular expression/java/and all of the containing substring "Java" String. Although the other characters in the regular expression are not matched by literal meaning, they all have special meanings. The regular expression/s$/contains two characters. The first special character "S" is the literal meaning of matching itself. The second character "$" is a special character that matches the end of the string. So the regular expression/s$/matches the string that ends with the letter "s".
1. Direct measure character
We have found that in regular expressions all alphabetic characters and numbers are matched by literal meaning to themselves. JavaScript Regular expressions also support some non-alphanumeric characters by escaping sequences that begin with a backslash (\). For example, the sequence "\ n" matches a literal newline character in a string. In regular expressions, many punctuation marks have special meanings. Here are the characters and their meanings:
The direct measure character of a regular expression
Character matching
________________________________
Alpha-numeric characters themselves
\ F Page Feed
\ n Line Feed
\ r Carriage Return
\ t tab
\ v Vertical Tab
\/One/Direct quantity
\ \ A \ Direct quantity
\ . One. Direct quantity
* A * Direct quantity
\ + A + direct quantity
\ ? One? Direct quantity
\ | One | Direct quantity
\ (One (direct quantity
) A direct amount
\ [one [Direct quantity
\] A direct amount
\ {a {Direct amount
\} A direct amount
\ XXX ASCII code characters specified by decimal number xxx
\ xnn ASCII code characters specified by the hexadecimal number nn
\ CX control character ^x. For example, \ci is equivalent to \ t, \CJ is equivalent to \ n
___________________________________________________
If you want to use special punctuation marks in regular expressions, you must precede them with a "\".
2. Character class
You can combine individual direct characters into a character class by putting them in brackets. A character class matches any of the characters it contains, so the regular expression/[ABC]/And the letter "a", "B", and "C" all match. In addition, you can define a negative character class, These classes match all characters except those contained within the brackets. To define a negative character tip, use a ^ symbol as the first character from the left bracket. The collection of regular expressions is/[a-za-z0-9]/.
Because some character classes are very common, the regular expression syntax for JavaScript contains special characters and escape sequences to represent these commonly used classes. For example, \s matches spaces, tabs, and other whitespace characters, and \s matches any character other than whitespace.
Regular table-Gray character classes
Character matching
____________________________________________________
[...] Any character that is within the parentheses
[^...] Any character not in parentheses
. Any character other than a line break, equivalent to [^\n]
\w any single word character, equivalent to [a-za-z0-9]
\w any non-word character, equivalent to [^a-za-z0-9]
\s any whitespace, equivalent to [\ t \ n \ r \ f \ V]
\s any non-white-space character, equivalent to [^\ t \ n \ r \ f \ V]
\d any number, equivalent to [0-9]
\d any character other than a number, equivalent to [^0-9]
[\b] A backspace direct amount (special case)
________________________________________________________________
3. Copy
With the above regular table syntax, you can describe a two-digit number AS/d/d/, describe four digits AS/\d \ d \ d \ d/. But we don't have a way to describe a number with any number of digits or a string. This string consists of three characters and a number following the letter. This Some complex patterns use regular expression syntax that specifies the number of times each element in the expression repeats.
Specifies that the copied characters always appear after the mode in which they are acting. Because some types of replication are fairly common. So there are some special characters that are specifically used to represent them. For example, the + number matches the pattern of copying the previous pattern one or more times. The following table lists the replication syntax. First look at an example:
/\d{2, 4}///match numbers between 2 and 4.
/\W{3} \d?///Match three single characters and an arbitrary number.
/\s+java\s+///matches the string "Java", and can have one or more spaces before and after that string.
/[^ "] *///Match 0 or more non-quote characters.
Copy character of regular expression
Character meaning
__________________________________________________________________
{n, m} matches the previous item at least n times, but not more than m times
{n,} matches n times before, or multiple
{n} matches the previous item exactly n times
? Matches the previous item 0 or 1 times, which means the previous item is optional. Equivalent to {0, 1}
+ matches 1 or more times before, equivalent to {1,}
* Match the previous item 0 or more times. Equivalent to {0,}
___________________________________________________________________
4. Select, Group and reference
The syntax of a regular expression also includes specifying a selection, grouping the subexpression, and referencing the special characters of the previous subexpression. Character | Used to separate the characters for selection. For example:/ab|cd|ef/matches the string "AB", or the string "CD", or "EF". /\d{3}| [A-z] {4}/matches either a three-digit number or four lowercase letters. Parentheses have several functions in regular expressions. Its main function is to separate the items into a subexpression so that it can be treated like a separate unit with *, +, or. To deal with those projects. For example:/java (script)?/matches the string "Java", which can be either "script" or not. /
(AB|CD) + |ef)/match can be either the string "EF" or the string "AB" or "CD" once or multiple repetitions.
In a regular expression, the second purpose of parentheses is to define the child mode in the complete pattern. When a regular expression succeeds in matching the target string, the You can extract the part of the target string that matches the child pattern in parentheses. For example, suppose that the pattern we are retrieving is followed by one or more digits, then we can use the pattern/[A-z] + \ d+/. But since we're supposed to be really concerned with the numbers of each matching tail, so if we put the numeric portion of the pattern in parentheses (/[A-Z] + (\d+)/), we can extract the numbers from any matches retrieved, and then we'll parse that.
Another use of the parenthetical subexpression is to allow us to refer to the preceding subexpression after the same regular expression. This is done by adding one or more digits to the string. The number refers to the position of the subexpression of the bracket in the regular expression. For example: \1 refers to the first parenthesis subexpression. \3 refers to the third bracket subexpression. Note that because the subexpression can be nested within other subexpression,
So its position is the position of the left parenthesis to be counted.
For example, the following regular expression is specified as \ 2:
/([Jj]ava ([Ss]cript)) \sis \s (fun\w*)/
The reference to the previous subexpression in the regular expression specifies not the pattern of that subexpression, but the text that matches that pattern. So the reference is not just a quick way to help you enter the repeating part of the regular expression.
Czech Republic, it also implements a statute, which is that the separate parts of a string contain exactly the same characters. For example, the following regular expression matches all characters that are within a single or double quotation mark. However, it requires quotation marks that start and end to match (for example, two are double quotes or single quotes):
/[' "] [^ ' "]*[' "]/
If you require quotation marks to match the start and end, we can use the following reference:
/([' "]) [^ '"] * \1/
\1 matches the pattern that is matched by the first parenthetical subexpression. In this example, it implements a specification that the opening quotation marks must match the closing quotation marks. Note that if the backslash follows a number more than the number of subexpression brackets, then it is parsed into a decimal escape sequence. Instead of a reference. You can avoid confusion by insisting that you use the full three characters to represent the escape sequence. For example, use \044 instead of \44. The following are the selection, grouping, and reference characters for regular expressions:
Character meaning
____________________________________________________________________
| Select the. Match either the subexpression to the left of the symbol, or the subexpression on its right side
(...) Group. Divides several items into one unit. This unit can be made up of *, +,? and | symbols, and you can also remember the characters that match this group for subsequent citation
With use
\ n matches the characters that are matched by the nth group. The grouping is a subexpression (possibly nested) in parentheses. The group number is a left to right count of the number of left parentheses
____________________________________________________________________
5. Specify a matching location
We have seen that many elements in a regular expression can match one character of a string. For example: \s matches just a blank character. There are also some regular expression elements that match the space between characters with a width of 0, rather than the actual characters such as: \b matches the bounds of a word, That is, the boundary between a/w character and a \w character. A character like \b does not specify a character in any matching string. They specify a valid location for the match to occur. Sometimes we call these elements anchors of regular expressions. Because they position the pattern in a particular position in the retrieval string. The most commonly used anchor element is ^, which makes the pattern dependent on the beginning of the string, while the anchor element $ causes the pattern to be positioned at the end of the string.
For example, to match the word "javascript", we can use regular expressions/^ JavaScript $/. If we want to retrieve the word "Java" itself (not as a prefix in "JavaScript"), then we can use the pattern/\s Java \s/, which requires spaces before and after the word java. But there are two problems with this. First: If "Java" appears in the The beginning or end of a character. The pattern will not match unless there is a space at the beginning and end. Second: When this pattern finds a matching character, it returns a matching string with spaces at the front and back end, which is not what we want. Therefore, we use the boundary \b of words to replace the real spaces \s. The resulting expression is the/\b Java \b/.
The following are the anchor characters for the regular expression:
Character meaning
____________________________________________________________________
^ matches the beginning of a character, and in multiple-line retrieval, it matches the beginning of a line
The $ match is the end of the character, and in multiple-row retrieval, the match is the end of a line
\b matches the boundary of a word. In short, the position between the character \w and the \w (note: [\b] matches backspace)
\b A character that matches the bounds of a non-word
_____________________________________________________________________
6. Property
The syntax for regular expressions also has the last element, that's the property of the regular expression, which shows the rules for advanced pattern matching. Unlike other regular expression syntaxes, attributes are described outside of the/symbol. That is, they do not appear between the two slashes, but are positioned after the second slash. JavaScript 1.2 supports two properties. Attribute I indicates that pattern matching should be case insensitive. Property g indicates that pattern matching should be global. Also
That is, you should find all the matches in the retrieved string. These two properties combine to perform a global, case insensitive match.
For example, to perform a case-insensitive retrieval to find the word "Java" (or "Java", "Java", and so on), we can use regular expressions that are insensitive to/\b java\b/i. If you want to find all the "Java" values in a string, we You can also add property g, which is the/\b Java \b/gi.
The following are the properties of the regular expression:
Character meaning
_________________________________________
I perform case insensitive matching
G to perform a global match, in short, is to find all the matches, instead of stopping after the first one is found.
_________________________________________
In addition to the properties G and I, regular expressions have no other attribute-like attributes. If you set the static property multiline of the constructor RegExp to true, pattern matching will be in a multiline mode. In this mode, the anchor characters ^ and $ match not just the beginning of the retrieved string and the Ends, and also matches the beginning and end of a line within the retrieved string. For example: pattern/java$/matches "Java" but does not match
"Java\nis fun". If we set the multiline attribute, the latter will also be matched:
Regexp.multiline = true;
In JavaScript, determine whether a string is in the form of an e-mail message:
Copy Code code as follows:
if (Formname.email.value!=formname.email.value.match (/^\w +[@]\w +[.) [\w.] +$/))
{
Alert ("Your e-mail format is wrong!") ");
Formname.email.focus ();
return false;
}
[Red]function dateverify (date) {
var reg =/^ (\d{4}) (-) (\d{2}) \2 (\d{2}) $/;
var r = Date.match (reg);
if (r==null) return false;
var d= new Date (r[1], r[3]-1,r[4]);
var newstr=d.getfullyear () +r[2]+ (D.getmonth () +1) +r[2]+d.getdate ();
date=r[1]+r[2]+ ((r[3]-1) +1) +r[2]+ ((r[4]-1) +1);
return newstr==date;
}[/red]
17 kinds of regular expressions for JavaScript
"^\\d+$"//non-negative Integer (positive integer + 0)
"^[0-9]*[1-9][0-9]*$"//Positive integer
"^ ((-\\d+) | (0+)) $ "//non-positive integer (negative integer + 0)
"^-[0-9]*[1-9][0-9]*$"//Negative integer
"^-?\\d+$"//Integer
"^\\d+ (\\.\\d+)? $"//nonnegative floating-point number (positive float + 0)
"^ ([0-9]+\\. [0-9]*[1-9][0-9]*) | ([0-9]*[1-9][0-9]*\\. [0-9]+) | ([0-9]*[1-9][0-9]*)] $ "//Positive floating-point number
"^ ((-\\d+ (\\.\\d+)?) | (0+ (\\.0+)) $ "//non-positive floating-point number (negative floating-point number + 0)
^ (-([0-9]+\\. [0-9]*[1-9][0-9]*) | ([0-9]*[1-9][0-9]*\\. [0-9]+) | ([0-9]*[1-9][0-9]*))] $ "//negative floating-point number
"^ (-?\\d+) (\\.\\d+)? $"//floating-point number
"^[a-za-z]+$"//A string of 26 English letters
"^[a-z]+$"//A string of 26 uppercase letters
"^[a-z]+$"///a string consisting of 26 lowercase letters
"^[a-za-z0-9]+$"//A string of numbers and 26 English letters
"^\\w+$"//A string of numbers, 26 English letters, or underscores
"^[\\w-]+ (\\.[ \\w-]+) *@[\\w-]+ (\\.[ \\w-]+) +$ "//email address
"^[a-za-z]+://(\\w+ (-\\w+) *) (\ \\w+ (-\\w+) *)) * (\\?\\s*) $ "//url
Properties and methods of regular expression objects
Predefined regular expressions have the following static properties: Input, Multiline, Lastmatch, Lastparen, Leftcontext, Rightcontext, and $ $. Where input and multiline can be preset. The values of other properties are assigned different values according to different conditions after the exec or test method has been executed. Many attributes have both long and short (Perl-style) two names, and the two names point to the same value. (JavaScript simulates Perl's regular expression)
The properties of the regular Expression object
attribute meaning
$1...$9 if it exists, it is the substring of the match.
$_ See input
$* See Multiline
$& See Lastmatch
$+ See Lastparen
$ ' See Leftcontext
$ ' See Rightcontext
constructor creates a special function prototype for an object
Whether global matches in the entire string (bool type)
Whether to ignore case (bool type) when IgnoreCase matches
Input is matched string
Lastindex the last matching index
Lastparen a substring enclosed in the last bracket
Leftcontext last match with left substring
Multiline whether multiple rows are matched (bool type)
Prototype allows attributes to be attached to objects
Rightcontext last match with the right substring
SOURCE Regular expression pattern
Lastindex the last matching index
Methods of regular Expression objects
Method meaning
Comparison of compile regular expressions
EXEC Perform Lookup
Test to match
Tosource returns the definition of a particular object (literal representing), whose value can be used to create a new object. Overloaded Object.tosource method is obtained.
ToString returns a string for a particular object. Overloaded Object.ToString method is obtained.
valueof returns the original value of a particular object. The method of overloading object.valueof
Example
Copy Code code as follows:
<script language = "JavaScript" >
var Myreg =/(w+) s (w+)/;
var str = "John Smith";
var newstr = str.replace (Myreg, "$, $");
document.write (NEWSTR);
</script>
Will output "Smith, John"
JavaScript Regular expression Test
Copy Code code as follows:
The checksum is all made up of numbers
function IsDigit (s)
{
var patrn=/^[0-9]{1,20}$/;
if (!patrn.exec (s)) return false
return True
}
Verify Login Name: Can only enter 5-20 letters beginning with a letter, can be with numbers, "_", "." The string
function Isregisterusername (s)
{
var patrn=/^[a-za-z]{1} ([a-za-z0-9]|[. _]) {4,19}$/;
if (!patrn.exec (s)) return false
return True
}
Verify user name: You can enter only 1-30 strings that start with a letter
function Istruename (s)
{
var patrn=/^[a-za-z]{1,30}$/;
if (!patrn.exec (s)) return false
return True
}
Verify password: Can only enter 6-20 letters, numbers, underscores
function ispasswd (s)
{
var patrn=/^ (\w) {6,20}$/;
if (!patrn.exec (s)) return false
return True
}
Check ordinary telephone, fax number: You can "+" start, in addition to numbers, can contain "-"
function Istel (s)
{
var patrn=/^[+]{0,1} (\d) {1,3}[]? ([-]? (\d) {1,12}) +$/;
var patrn=/^[+]{0,1} (\d) {1,3}[]? ([-]? ((\d) | []) {1,12}) +$/;
if (!patrn.exec (s)) return false
return True
}
Check mobile phone Number: Must start with a number, in addition to the number, can contain "-"
function Ismobil (s)
{
var patrn=/^[+]{0,1} (\d) {1,3}[]? ([-]? ((\d) | []) {1,12}) +$/;
if (!patrn.exec (s)) return false
return True
}
Check ZIP code
function Ispostalcode (s)
{
var patrn=/^[a-za-z0-9]{3,12}$/;
var patrn=/^[a-za-z0-9]{3,12}$/;
if (!patrn.exec (s)) return false
return True
}
Verify Search Keywords
function Issearch (s)
{
var patrn=/^[^ ' ~!@#$%^&* () +=|\\\][\]\{\}:; ' \,.<>/?] {1} [^ ' ~!@$%^& () +=|\\\] [\]\{\}:;' \,.<>?] {0,19}$/;
if (!patrn.exec (s)) return false
return True
}
function IsIP (s)//by zergling
{
var patrn=/^[0-9.] {1,20}$/;
if (!patrn.exec (s)) return false
return True
}
Regular expression Regular expression detailed (i)
Regular expression is regular expression, it seems that English is better than Chinese understand more, is to check expression characters
Not meet the rules!! Regular expressions have a very powerful and complex object regexp, provided in the JavaScript1.2 version.
Let's look at an introduction to regular expressions:
Regular expression objects are used to standardize an expression of a specification (that is, an expression character that does not meet a specific requirement, such as an email address format, etc.), and it has properties and methods for checking whether the given string conforms to the rules.
In addition, the properties of the individual regular expression objects that you set up with the RegExp constructor have predefined static properties of regular expression objects that you can use at any time.
Core objects:
In JavaScript 1.2, NES more than 3.0 versions are available.
After the JavaScript 1.3 version added the Tosource method.
To establish a method:
Text formatting or regexp constructor functions.
Text formatting uses the following format:
/pattern/flags/Mode/tag
The constructor function method uses the following methods:
New RegExp ("pattern" [, "Flags"]) is new REGEXP ("mode" [, "tag"])
Parameters:
Pattern (Mode)
Text that represents the regular expression
Flags (tags)
If you specify this item, flags can be one of the following denominations:
G:global match (full set matching)
I:ignore case (ignoring capitalization)
Gi:both Global Match and ignore case (matches all possible values, also ignores capitalization)
Note: The parameters in the text format do not use quotation marks, and constructor function parameters are marked with quotation marks. So the following expression establishes the same regular expression:
/ab+c/i
New RegExp ("Ab+c", "I")
Describe:
When using constructors, it is necessary to use normal string avoidance rules (adding leading characters in a string).
For example, the following two statements are equivalent:
Re = new RegExp ("\\w+")
Re =/\w+/
The following provides a complete list and description of the special characters that can be used in regular expressions.
Table 1.3: Special characters in regular expressions:
Characters
Meaning: For a character, it is usually a literal meaning that the character followed by a special character is not interpreted.
For example:/b/matches the character ' B ' by adding a backslash, or/\b/, before B, which becomes a special character that matches the line of a word.
Or:
For a few characters, usually the description is special, indicating that the character immediately followed is not special, but should be interpreted literally.
For example: * is a special character that matches any character (including 0 characters), for example:/a*/means matching 0 or more aces.
To match the literal *, precede a with a backslash; For example:/a\*/matches a ' * '.
Character ^
Meaning: The character that matches must be at the front.
For example:/^a/does not match the ' a ' in ' an A ', but matches ' an A. ' The "A" in the front.
Character $
Meaning: Similar to ^, matches the last character.
For example:/t$/does not match ' t ' in ' eater ', but matches ' t ' in ' eat '.
Characters
Meaning: matches the characters of the preceding 0 or n times.
For example:/bo*/matches ' B ' in ' boooo ' or ' a bird warbled ' in ' a ghost booooed ', but does not match any character in ' a goat grunted '.
Character +
Meaning: Matches the character preceded by the + number 1 or n times. Equivalent to {1,}.
For example:/a+/matches ' a ' and ' Caaaaaaandy ' in ' Candy '. All ' a ' in.
Character?
Meaning: match the preceding character 0 or 1 times.
For example:/e?le?/matches ' el ' and ' angle ' in ' Angel '. ' Le ' in the.
Character.
Meaning: (decimal point) matches all individual characters except for line breaks.
For example:/.n/matches ' an ' and ' on ' in the ' nay ', an apple are on the tree, but does not match ' nay '.
Character (x)
Meaning: Matches ' X ' and records the matching value.
For example:/(foo)/Match and record "Foo bar." In the ' foo '. The matching substring can be obtained by the element [1] In the result array, ..., [n] returned, or the property of the RegExp object is $ ..., the return of the $.
Character X|y
Meaning: Match ' x ' or ' Y '.
For example:/green|red/matches ' green ' and ' Red apple ' in ' green apple '. In the ' Red '.
Character {n}
Meaning: Here The n is a positive integer. Matches the preceding n characters.
For example:/a{2}/does not match "a" in "Candy," but matches "Caandy," all ' a ' and "Caaandy." Two in front of
' A '.
Character {n,}
Meaning: Here The n is a positive integer. Matches at least n preceding characters.
For example:/a{2,} does not match ' a ' in ' Candy ', but matches all ' a ' and ' Caaaaaaandy ' in ' Caandy '. All ' a ' in the
Character {n,m}
Meaning: Here the N and M are all positive integers. Matches at least n up to m preceding characters.
For example:/a{1,3}/does not match any of the characters in "Cndy", but matches the first two in "a", "Caandy," in "Candy,"
"A" and "Caaaaaaandy" in front of the three ' a ', note: even if "caaaaaaandy" there are many ' a ', but only match the preceding three ' a ' that is ' AAA '.
character [XYZ]
Meaning: A list of characters that matches any one of the characters listed. You can indicate a range of characters through hyphens.
For example: [ABCD] is the same as [a-c]. They match the ' C ' in ' B ' and ' ache ' in ' brisket '.
character [^XYZ]
Meaning: A character complement, that is, it matches everything except the characters listed. You can use hyphens--to indicate a range of characters.
For example: [^ABC] and [^a-c] are equivalent, they first match the ' R ' and ' chop ' in ' brisket '. In the ' H '.
character [\b]
Meaning: Match a space (do not confuse with \b)
Character \b
Meaning: A line that matches a word, such as a space (not confused with [\b])
For example:/\bn\w/matches ' no ' in ' Noonday ',/\wy\b/matches ' possibly yesterday. ' In the ' ly '.
Character \b
Meaning: A non-dividing line that matches a word
For example:/\w\bn/matches ' on ' in ' Noonday ',/y\b\w/matches ' possibly yesterday. ' In the ' ye '.
Character \cx
Meaning: Here The X is a control character. Matches the control character of a string.
For example:/\cm/matches the control-m in a string.
Character \d
Meaning: Matches a number, equivalent to [0-9].
For example:/\d/or/[0-9]/matches "B2 is the" suite number. In the ' 2 '.
Character \d
Meaning: Matches any non-numeric, equivalent to [^0-9].
For example:/\d/or/[^0-9]/matches "B2 is the" suite number. In the ' B '.
Character \f
Meaning: matches a form character
Characters \ n
Meaning: matches a newline character
Character \ r
Meaning: matches a carriage return character
Character \s
Meaning: Matches a single white spaces, including spaces, tab,form feeds, line breaks, equivalent to [\f\n\r\t\v].
For example:/\s\w*/matches "foo bar." ' Bar ' in the.
Character \s
Meaning: matches a single character except white spaces, equivalent to [^ \f\n\r\t\v].
For example:/\s/\w* matches "foo bar." In the ' foo '.
Character \ t
Meaning: Match a tab
Character \v
Meaning: Match a head tab
Character \w
Meaning: Matches all numbers and letters and underscores, equivalent to [a-za-z0-9_].
For example:/\w/matches ' 5 ' and ' 3D ' in ' a ', ' $5.28, ' in ' Apple, '. In the ' 3 '.
Character \w
Meaning: Matches other characters except numbers, letters, and underscores, equivalent to [^a-za-z0-9_].
For example:/\w/or/[^ $A-za-z0-9_]/match "50%." In the '% '.
Characters \ n
Meaning: Here The n is a positive integer. Matches the value of N of the last substring of a regular expression (counting the left parenthesis).
For example:/apple (,) \sorange\1/match "Apple, orange, cherry, peach." In the ' Apple, Orange ', here is a more complete example.
Note: If the number in the left parenthesis is smaller than the number specified in \ n, then \ n takes a row of octal escape as a description.
Character \ooctal and \xhex
Meaning: The \ooctal here is a octal escape value, and \xhex is a hexadecimal escape value that allows ASCII code to be embedded in a regular expression.
When an expression is checked, a literal symbol provides a way to edit the regular expression. You can use a literal symbol to keep the regular expression constant. For example, if you use a literal symbol to construct a regular expression in a loop, the regular expression does not need to be compiled repeatedly.
The regular Expression object builder, for example, new RegExp ("Ab+c"), provides run-time compilation of regular expressions. When you know that the patterns of regular expressions change, you should use constructors, or you don't know the pattern of regular expressions, when they are obtained from another source, such as when entered by a user. Once you have defined the regular expression, the regular expression can be used anywhere and can be changed, and you can use the compile method to compile a new regular expression for reuse.
A separate predefined RegExp object can be used in each window, that is, each detached JavaScript thread runs to get its own RegExp object. Because each script is non-disruptive in one thread, this ensures that different scripts do not overwrite the value of the RegExp object.
Predefined RegExp objects contain static properties: Input, Multiline, Lastmatch,lastparen, Leftcontext, Rightcontext, and from $ to $. Input and Multiline properties are preset. The values of other static properties are set after the exec and test methods of the individual regular expression objects are executed, and after the match and replace methods of the string are executed.
Property
Note that several properties of the RegExp object have both long and short names (like Perl). These names all point to the same value. Perl is
A programming language, while JavaScript imitates its regular expression.
Properties $, ..., $
Gets a matching substring, if any.
Attribute $_
Reference input
Attribute $*
Reference Multiline
Attribute $&
Reference Lastmatch
Attribute $+
Reference Lastparen
Attribute $ '
Reference Leftcontext
Attribute $ '
Reference Rightcontext
Attribute constructor
Specify the object to be used to create the prototype letter
Attribute Global
Determines whether to test whether a regular expression cannot match all strings, or just the first conflict.
Attribute ignorecase
Determines whether case is ignored when trying to match a string
Attribute input
When the regular expression is matched, the string is the opposite.
Attribute lastindex
Decide where the next match starts
Attribute Lastmatch
Last matching character
Attribute Lastparen
SUBSTRING matches when the last parenthesized, if any.
Attribute Leftcontext
Substring before the most recent match.
Attribute Multiline
Whether to search in multiple lines of a string.
Attribute prototype
Allow attributes to be attached to all objects
Attribute Rightcontext
Substring of the most recent match.
Property source
Modal text
Method
Compile method
Compiling a regular Expression object
exec method
Run regular expression matching
Test method
Test regular up-match
Tosource method
Returns the object specified by the text description of an object; You can use this value to create a new object. Don't consider Object.tos
Ource method.
ToString Method
Returns a string describing the specified object, regardless of the Object.ToString object.
ValueOf method
Returns the original value of the specified diagonal. Do not consider the Object.valueof method.
In addition, this object inherits the watch and Unwatch methods of the object
Example:
Example 1, the following example script uses the Replace method to convert words in a string. In the replaced text, the script uses the value of the $ and $ property of the global RegExp object. Notice the name of the $ property of the RegExp object when passed to the Replace method as the second argument.
<script language= "JavaScript1.2" >
Re =/(\w+) \s (\w+)/;
str = "John Smith";
Newstr=str.replace (Re, "$ $");
document.write (NEWSTR)
</SCRIPT>
Show results: "Smith, John".
Example 2, the following example script, regexp.input by the change event handles the handle setting. In the GetInfo function, the Exec method
Using the value of regexp.input as its argument, note that the $ attribute is regexp preset.
<script language= "JavaScript1.2" >
function GetInfo (ABC)
{
Re =/(\w+) \s (\d+)/;
Re.exec (Abc.value);
Window.alert (regexp.$1 + ", your is" + regexp.$2);
}
</SCRIPT>
Please enter your last name and age and press ENTER when you are finished.
<form><input type= "TEXT" name= "Nameage" onchange= "getInfo (this);" ></FORM>
</HTML>
$, ..., $ property
A matching substring enclosed in parentheses, if any.
Is the property of the RegExp
Static, read-only
In JavaScript 1.2, NES version 3.0 offers
Description: Because input is a static property, it is not a property of an individual regular expression object. You can access this property using Regexp.input.
The number of substrings that can be prefixed with parentheses is unrestricted, but the regular expression object can only retain the last 9 bars. If you want to access all the parentheses inside the matching string, you can use the returned array.
These properties can be replaced by the Regexp.replace method (output). When you use this method, you do not have to consider the RegExp object beforehand. An example is given below. When the regular expression does not include parentheses, the script interprets the literal meaning of the $n. (Here's n is a positive integer).
For example:
The following example script uses the Replace method to swap the position of a word in a string. In the replaced text string, the script uses the regular expression
The value of the $ and $ property of the RegExp object. Note: When they pass parameters to the Replace method, there is no consideration for the $ attribute
The name of the RegExp object.
<script language= "JavaScript1.2" >
Re =/(\w+) \s (\w+)/;
str = "John Smith";
Newstr=str.replace (Re, "$ $");
document.write (NEWSTR)
</SCRIPT>
The output displayed is: Smith, John.
Regular expression Regular expression detailed (II.)
Regular Expressions in detail (II.)
The following are new objects that are not regular expressions see the corresponding JavaScript object's Properties $_ Property Reference Input $* property
Reference Multiline $& Property Reference Lastmatch $+ Property Reference Lastparen $ ' property
Reference Leftcontext $ ' Property Reference Rightcontext compile method to compile regular expression objects during script run
Methods belonging to RegExp provide syntax in JavaScript 1.2, NES over 3.0 versions:
Regexp.compile (pattern[, flags]) in number: RegExp the name of a regular expression, either a variable name or a string of text.
The definition text of the pattern regular expression. Flags, if specified, can be one of the following: "G": match all possible strings
"I": Ignores Case "GI": matches all possible strings and ignores case descriptions:
Use the Compile method to compile a regular expression created with the RegExp constructor function. Such
Forces the regular expression to compile only once, not every time a regular expression is encountered. When you confirm that the regular expression is capable of
You can use the compile method to compile it (after you get its matching pattern) so that it is repeated multiple times in your script.
You can also use the Compile method to change the regular expression during run time. For example, if the regular expression is changed,
You can use the compile method to recompile the object to improve efficiency.
Using this method will change the value of the source, global, and Ignorecasesource properties of the regular expression. Constructor
Indicates the function that establishes the object prototype. Note that the value of this property is provided by the function itself, not by a string containing the RegExp name.property.
In JavaScript 1.1, NES 2.0 version provides ECMA version ECMA-262 description: Reference object.constructor.
The Exec method runs a matching search in the specified string. Returns an array of results. It's a regexp way.
In JavaScript 1.2, NES version 3.0 provides syntax: Regexp.exec ([str]) regexp ([str])
Parameters: RegExp, the name of the regular expression, can be a variable name or a text definition string.
STR, to match the string of the regular expression, if omitted, the value of the regexp.input is used.
Description: As in the syntax description, the Exec method of a regular expression can be invoked directly (using Regexp.exec (str)) or indirectly (using RegExp (str)).
If you're just running to find out if it matches, you can use string search methods.
If the match succeeds, the Exec method returns an array and updates the value of the regular Expression object property and the predefined regular expression object, RegExp. If the match fails, the Exec method returns NULL.
Take a look at the following example: <script language= "JavaScript1.2" >//Match one B followed by one or more d, then another B
Ignores case myre=/d (b +) (d)/ig; MyArray = Myre.exec ("Cdbbdbsbz");
</SCRIPT> below is the return value of the script: Object attribute/index Description Example
MyArray
MyArray content ["DBBD", "BB", "D"]
Index
0-based matching index 1
Input
Raw String CDBBDBSBZ
[0]
Last-matched character dbbd
[1], ... N
A matching string enclosed in parentheses, if any. Does not limit the number of parentheses. [1] = BB
[2] = d
Myre
Lastindex
Index value of starting next match operation 5
IgnoreCase
Indicates whether "I" is used to ignore case true
Global
Indicates whether the "G" tag is used to match all possible string true
Source
A text string that defines the pattern D (b +) (d)
Regexp
lastmatch$&
Last-matched character dbbd
Leftcontext$\q
Latest Match substring C in front
rightcontext$ '
Substring BSBZ after the latest match
$, ...
The matching substring within the parentheses, if any. The number of parentheses is unrestricted, but RegExp can only retain the last 9 $ = BB
$ = d
Lastparen $+
The last matching substring with parentheses, if any, D
If your regular expression uses the "G" tag, you can use the Exec method multiple times to match the same string consecutively. When you do this, the new match starts in a substring determined by the Lastindex property value of the regular expression. For example, suppose you use the following script:
<script language= "JavaScript1.2" > myre=/ab*/g;str = "Abbcdefabh"
myarray = myre.exec (str);
Document.writeln ("Found" +myarray[0]+). Next match starts at "+myre.lastindex"
Mysecondarray = myre.exec (str);
Document.writeln ("Found" +mysecondarray[0]+). Next match starts at "+myre.lastindex"
</SCRIPT>
This script shows the following results: Found ABB. Next Match starts at 3
Found AB. Next Match starts at 9 example:
In the following example, the user enters a name, and the script performs a matching operation based on the input. Then check the array to see if it matches the other user's name.
This script assumes that the last name of the registered user has been stored in array A and may be obtained from a database.
<HTML>
<script language= "JavaScript1.2" > A = ["Zhao", "Qian", "Sun", "Li", "Liang"]
function lookup () {firstName =/\w+/i (); if (!firstname)
Window.alert (regexp.input + "illegal input"); else {count=0;
For (I=0;i enter your last name and press ENTER.)
<form><input TYPE: "TEXT" Name= "FirstName" onchange= "lookup (this);" ></FORM>
</HTML>
Whether the "G" tag is used in the
global property regular expression. RegExp property, read-only
in JavaScript 1.2, NES version 3.0 provides a description: Global is a property of an individual regular expression object
if the "G" tag is used, the global value is true; otherwise, false. The "G" tag specifies that the regular expression tests all possible matches.
You can't change the value of the property directly, but you can call the compile method to change it. IgnoreCase checks whether the regular expression uses the "I" tag
RegExp property, reads only in JavaScript 1.2, and NES version 3.0 provides a description:
IgnoreCase is an attribute of an individual regular expression object. The
returns True if the "I" tag is used, or false. The "I" tag indicates that case is ignored when a match is made.
You can't change the value of the property directly, but you can change it by calling the compile method. Input indicates that the regular expression tests that string. $_ is another name for this attribute.
RegExp Properties, static in JavaScript 1.2, NES more than 3.0 versions available
Description: Because input is static, it is not a property of an individual regular expression object. You can also use Regexp.input to express.
If you do not supply a string to the Exec or test method of the regular expression, and if there is a value in the Regexp.input, the method is invoked using its value.
The script or browser can preset the input property. If a value is preset and a string is not supplied when calling the Exec or test method
The value of input is used when calling exec or test. Input can be set by the browser in the following way:
When the text form field processing handle is invoked, input is set to the string of the text input.
When the textarea form field processing handle is invoked, input is set to the string entered in the TextArea field. Pay attention to Multili
NE is also set to true to match multiple lines of text. When the Select form field processing handle is invoked, input is set to the value of selected text.
When the processing handle of a linked object is invoked, input is set to a string between the <a href=...> and the </A>.
The value of the input property is cleared when the event-handler handle is finished. Lastindex a readable/writable integer property that indicates where the next match starts.
RegExp's properties are available in JavaScript 1.2, NES version 3.0 above
Description: Lastindex is the property of an individual regular expression object. This property is set only when the "G" tag of the regular expression is used to perform a full string match. The following rules apply:
If the length of the lastindex size string, regexp.test and regexp.exec fail, and the lastindex is set to 0.
If the lastindex equals the length of the string and the regular expression matches the empty string, the regular expression starts at the lastindex position.
If the lastindex equals the length of the string and the regular expression does not match the empty string, the regular expression does not match the input and the lastindex is set to 0.
Otherwise, the lastindex is set to the next point of the last match. For example, execute the script in the following order: RE =/(HI)?/g match empty string
Re ("HI") returns ["Hi", "Hi"],lastindex to 2
Re ("HI") returns ["], an empty array whose subscript 0 element is the matching string. In this case, return null
The string is because the lastindex equals 2 (and still is 2), and "HI" is also 2. Lastmatch last match string,$& is the same meaning.
RegExp properties, static, read-only in JavaScript 1.2, NES 3.0 version offers
Description: Because lastmatch is static, it is not an attribute that specifies the regular expression individually. You can also use Regexp.lastmatch. Lastparen
The last time you enclose the matching string, if any. $+ is the same meaning. RegExp property, Static, read-only
In JavaScript 1.2, NES version 3.0 offers
Description: Because Lastparen is static, it is not an attribute of an individual regular type, you can use Regexp.lastparen to express the same meaning.
Leftcontext last match the preceding substring, $ ' has the same meaning. RegExp properties, static, read-only
In JavaScript 1.2, NES version 3.0 offers
Description: Because leftcontext is static, not a regular expression, you can use Regexp.leftcontext to express the same meaning.
Multiline reflect whether to match multiple lines of text, $* is the same meaning. RegExp Properties, static
In JavaScript 1.2, NES version 3.0 offers
Description: Because multiline is static rather than an attribute of an individual regular expression, it is possible to express the same meaning with regexp.multiline.
True if multiple lines of text is allowed, false if the search must stop on multiline.
The script or browser can set the Multiline property. When a textarea event-handling handle is invoked, the multiline
is set to true. The Multiline property value is cleared after the event handling handle has finished processing. In other words, if you set the multiline to true, the multiline is placed to false after any event handling handles are executed. Prototype
Describe the prototype of the class. You can use prototype to add properties or methods to your class as required. For information on prototypes, see the Function.prototype.Property property for RegExp. From JavaScript 1.1, NES version 2.0 starts offering
ECMA version ECMA-262 rightcontext the last matching string on the right, $ ' is the same effect.
RegExp properties, static, read-only from JavaScript 1.2, NES 3.0 above version started offering
Description: Because rightcontext is static, not an individual regular expression of the property, you can use Regexp.rightcontext to achieve the same effect.
Source is a read-only property that contains the pattern defined by the regular expression, not the forward slashes and "G" or "I" tags. RegExp Properties, Read only
From JavaScript 1.2, NES version 3.0 begins to provide
Description: Source is the property of an individual regular expression object, you can't change its value directly, but you can change it by calling the compile method. Test
Performs a regular-expression matching search for the specified string, returning True or false. The method of RegExp
From JavaScript 1.2, NES version 3.0 begins to provide syntax: Regexp.test ([str])
Parameters: RegExp, the name of the regular expression, either a variable name or a regular expression that defines a text string
STR, to match the string, if omitted, will use the value of regexp.input as the argument
Description: When you need to know if a string can match a regular expression, use the test method (with the String.search side
In order to obtain more information (but the speed will be slow), you can use the Exec method (similar to the String.match method). Example: The following example shows a hint that test is successful:
function Testinput (Re, str) {
if (Re.test (str)) midstring = "contains";
else midstring = "does not contain";
document.write (str + midstring + re.source); } Tosource
Returns a String representing the source code of the object RegExp syntax from JavaScript 1.3 above: Tosource ()
Parameter: No Description: The Tosource method returns the following value: For the built-in RegExp object, Tosource returns the following characters symbolizing the source code is not available:
function Boolean () {[native code]}
In regexp situations, Tosource returns a string of symbolic source code, which is usually invoked automatically by the JavaScript internal rather than by an explicit call.
More See Object.tosource toString returns a string depicting the specified object. The method of RegExp
From JavaScript 1.1, NES 2.0 begins to provide ECMA version ECMA-262 syntax: toString () Parameter: None
Description: The RegExp object does not consider the ToString method of object objects; it does not inherit object.tostring, for RegExp
Like, the ToString method returns a string representing the object. For example: The following example shows a string representing a RegExp object
Myexp = new RegExp ("A+b+c"); Alert (myexp.tostring ())
Displays "/a+b+c/" more see: Object.ToString valueof Returns the original value of a RegExp object
The RegExp method provides the ECMA version starting with the JavaScript 1.1 version: ECMA-262 syntax: valueof ()
Parameters: No Description: RegExp's ValueOf method returns the original value of the RegExp object as a string, which is equal to regexp.tostring.
This method is usually invoked automatically by JavaScript inside instead of an explicit invocation example: Myexp = new RegExp ("A+b+c");
Alert (myexp.valueof ()) displays "/a+b+c/"
Regular expressions in several instances of JavaScript in 1 (RPM)
! Remove the processing of whitespace on both ends of a string
If you take the traditional approach, you might want to take the following approach.
Copy Code code as follows:
Clear left Space
function Js_ltrim (DESTSTR)
{
if (deststr==null) return "";
var pos=0;
var retstr=new String (DESTSTR);
if (retstr.lenght==0) return retstr;
while (retstr.substring (pos,pos+1) = = "") pos++;
Retstr=retstr.substring (POS);
return (RETSTR);
}
Clear right space
function Js_rtrim (DESTSTR)
{
if (deststr==null) return "";
var retstr=new String (DESTSTR);
var pos=retstr.length;
if (pos==0) return retstr;
while (POS && retstr.substring (pos-1,pos) = "") pos--;
Retstr=retstr.substring (0,pos);
return (RETSTR);
}
Clear left and right spaces
function Js_trim (DESTSTR)
{
if (deststr==null) return "";
var retstr=new String (DESTSTR);
var pos=retstr.length;
if (pos==0) return retstr;
Retstr=js_ltrim (RETSTR);
Retstr=js_rtrim (RETSTR);
return retstr;
}
Using regular expressions, to remove the spaces on either side, just the following code
String.prototype.trim = function ()
{
Return This.replace (/(^\s*) | ( \s*$)/g, "");
}
One sentence is done,
The visible regular expression saves us a considerable amount of written code
! Check of mobile phone number
If you are using a traditional calibration method, you must complete the following three steps.
(1). Whether it is a number
(2). is 11-bit
(3). Whether the third digit is 5,6,7,8,9
If you use regular expression checksums, just the following code
Copy Code code as follows:
function CheckMobile1 (form)
{
if (Form.mobile.value > "")
{
var reg=/13[5,6,7,8,9]\d{8}/;
if (Form.mobile.value.match (reg) = null)
{
Alert ("Please enter the correct mobile phone number!") ");
Form.mobile.focus (); return false;
}
}
return true;
}
From the above code can be seen verified mobile phone number only need to define a var reg=/13[5,6,7,8,9]\d{8}/, pattern matching string can complete the validity of the check
! The checksum of the URL,
Condition: Must begin with http://or https://, the port number must be between 1-65535, the following code completes the validation of the legality
Copy Code code as follows:
OBJ: Data Objects
DISPSTR: Failure prompt Content Display string
function Checkurlvalid (obj, dispstr)
{
if (obj = null)
{
Alert ("Incoming object is null");
return false;
}
var str = obj.value;
var urlpatern0 =/^https?:\ /\/.+$/i;
if (!urlpatern0.test (str))
{
Alert (dispstr+ "illegal: Must start with ' http:\/\/' or ' https:\/\/')";
Obj.focus ();
return false;
}
var urlpatern2=/^https?:\ /\/([a-za-z0-9_-]) + (\.)?) * (: \d+)? +$/i;
if (!urlpatern2.test (str))
{
Alert (dispstr+ "port number must be a number and should be between 1-65535!");
Obj.focus ();
return false;
}
var urlpatern1 =/^https?:\ /\/([a-za-z0-9_-]) + (\.)?) * (: \d+)? (\/((\.)? (\?)? =?&? [a-za-z0-9_-] (\?)?) *) *$/i;
if (!urlpatern1.test (str))
{
Alert (dispstr+ "illegal, please check!");
Obj.focus ();
return false;
}
var s = "0";
var t = 0;
var re = new RegExp (": \\d+", "IG");
while ((arr = re.exec (str))!=null)
{
s = str.substring (Regexp.index+1,regexp.lastindex);
if (s.substring (0,1) = = "0")
{
Alert (dispstr+ "port number cannot begin with 0!");
Obj.focus ();
return false;
}
T = parseint (s);
if (t<1 | | t >65535)
{
Alert (dispstr+ "port number must be a number and should be between 1-65535!");
Obj.focus ();
return false;
}
}
return true;
}
To the URL of the checksum, it appears that there are a lot of code, this is because to give error prompts, otherwise just var urlpatern1 =/^https?:\ /\/([a-za-z0-9_-]) + (\.)?) * (: \d+)? (\/((\.)? (\?)? =?&? [a-za-z0-9_-] (\?)?) *) *$/i; You can verify that the URL is valid.
Regular expressions in JavaScript applications
--------------------------------------------------------------
Remove extra space from string and tail
/g is full-text lookup all matches
function String.prototype.Trim () {return this.replace (/^\s*) | ( \s*$)/g, "");
function String.prototype.LTrim () {return this.replace (/(^\s*)/g, "");}
function String.prototype.RTrim () {return this.replace (/(\s*$)/g, "");}
--------------------------------------------------------------
Application: Computes the length of the string (a double-byte character length meter 2,ascii character 1)
String.prototype.len=function () {return This.replace ([^\x00-\xff]/g, "AA"). Length;}
--------------------------------------------------------------
Application: JavaScript does not have a trim function like VBScript, we can use this expression to implement, as follows:
String.prototype.trim = function ()
{
Return This.replace (/(^\s*) | ( \s*$)/g, "");
}
You have to use regular expressions to extract the filename from the URL address of the JavaScript program, the following result is Page1
S= "Http://www.jb51.net/page1.htm"
S=s.replace (/(. *\/) {0,} ([^\.] +). */ig, "$"
Alert (s)
# #利用正则表达式限制网页表单里的文本框输入内容:
--------------------------------------------------------------
Only Chinese can be entered with regular expression restrictions: onkeyup= "Value=value.replace" (/[^\u4e00-\u9fa5]/g, ') "onbeforepaste=" Clipboarddata.setdata (' text ' , Clipboarddata.getdata (' text '). Replace (/[^\u4e00-\u9fa5]/g, ') "
--------------------------------------------------------------
Only full-width characters can be entered with regular expression restrictions: onkeyup= "Value=value.replace (/[^\uff00-\uffff]/g,") "Onbeforepaste=" Clipboarddata.setdata (' Text ', Clipboarddata.getdata (' text '). Replace (/[^\uff00-\uffff]/g, ') "
--------------------------------------------------------------
Only numbers can be entered with regular expression restrictions: onkeyup= "Value=value.replace" (/[^\d]/g, ') "onbeforepaste=" Clipboarddata.setdata (' text ', Clipboarddata.getdata (' text '). Replace (/[^\d]/g, ') "
--------------------------------------------------------------
Only numbers and English can be entered with regular expression restrictions: onkeyup= "Value=value.replace" (/[\w]/g, ') "onbeforepaste=" Clipboarddata.setdata (' text ', Clipboarddata.getdata (' text '). Replace (/[^\d]/g, ') "
Complete validation of forms with regular expressions and JavaScript
When using, save the following JavaScript code in a single JS file.
1. Form requirements
<form name= "FormName" onsubmit= "return Validateform (This)" ></form>
All of the following types of fields in the form will be validated in turn, all validation is to remove the leading and suffix spaces, and note that the case is case-sensitive.
2, null value verification
Any field in the form plus the Emptyinfo property verifies that the field is empty (can be used concurrently with the maximum length validation \ General authentication method).
No this property is considered to allow null values for this field.
such as: <input type= "text" name= "fieldnamename" emptyinfo= field can not be empty! ">
3. Maximum length verification (can be used at the same time as null verification, general authentication method):
<input type= "text" name= "Fieldnamename" maxlength= "" lengthinfo= "maximum length can not exceed 20! ">
Or, <textarea maxlength= "lengthinfo=" the maximum length can not exceed 2000! ">
3, the General verification method (do not verify the null value):
such as: <input type= "text" validator= "^ (19|20) [0-9]{2}$" errorinfo= "Incorrect year!" >
4. Standard verification (not used in conjunction with other verification methods):
All are implemented through the <input type= "hidden", and the Name property is not required to avoid submitting to the server.
4.1. Legal Date Verification:
<input type= "text" name= "Yearfieldname" value= ">" Note: This can also be <select name= "Yearfieldname" ></select ", with the same
<input type= "text" name= "Monthfieldname" value= ">"
<input type= "text" name= "Dayfieldname" value= ">"
<input type= "hidden" validatortype= "Dategroup" year= "Yearfieldname" month= "Monthfieldname" day= "DayfieldName" Errorinfo= "not the right date!" >
Yearfieldname, Monthfieldname, Dayfieldname are the days of the year, month and day can be two-bit (MM) or a format (M),
This is not a separate test for each field (if you want to test, please use the previous general verification method in three fields of year/year, respectively), only the maximum value of the date is legal check;
4.2, date format verification (please note that this validation does not validate the validity of the date, and has not found a way to get the year date data from the format ^_^):
<input type= "text" name= "Datefieldname" value= "2003-01-03 21:31:00" >
<input type= "hidden" validatortype= "Date" fieldname= "Datefieldname"; format= "Yyyy-mm-dd HH:mm:ss" errorinfo= "Incorrect date!" >
Where the format only supports Y, M, D, H, M, s (other characters as non time characters)
4.3. List verification:
Verify that the list (checkbox, Redio, select) has at least one record selected (for select is primarily for multiple selections)
<input type= "checkbox" Name= "CheckBox1" >
<input type= "hidden" validatortype= checkbox "Fieldname=" CheckBox1 "errorinfo=" Please select at least one record! " >
Where validatortype can be checkbox, R, Select;
For a select form, if you want to select a record that cannot be the first article, use the following methods:
<select name= "Select1" emptyinfo= "Please select an option!" >
<option value= "" >== Please choose ==</option>
<option value= "1" >1</option>
<select>
4.4, Email verification:
<input type= "text" name= "email" >
<input type= "hidden" fieldname= "email" validatortype= "email" separator= "," errorinfo= "Incorrect email!" >
Where separator is optional, indicating the delimiter when entering multiple emails (no such option can be an address only)
4.5, add other JavaScript operation:
<script type= "Text/javascript" >
function functionname () {
Custom Methods
}
</script>
Add <input type= "hidden" to the form validatortype= "JavaScript" functionname= "functionname" > (at this point the Emptyinfo and other properties are invalid)
The JavaScript method specified in the Function property is invoked (requiring the method to return true or FALSE, and returning false will no longer validate the form or submit the form).
5. Disable a button before the form is submitted through validation (you can also disable other fields and cannot be in one domain with other validation), and do not require the button to be the last one in the form
<input type= "button" name= "Submit" validatortype= "Disable" >
6, do not verify the form
<input type= "hidden" name= "Validate" value= "0" functionname= "functionname" >
Submits a form when the validator field value is 0 o'clock without verifying the form, submitting the form directly or executing the specified function and returning True
functionname is optional
Copy Code code as follows:
<script type= "Text/javascript" >
function Getstringlength (str) {
var endvalue=0;
var sourcestr=new String (str);
var TempStr;
for (var strposition = 0; strposition < sourcestr.length; Strposition + +) {
Tempstr=sourcestr.charat (strposition);
if (tempstr.charcodeat (0) >255 | | tempstr.charcodeat (0) <0) {
endvalue=endvalue+2;
} else {
endvalue=endvalue+1;
}
}
return (Endvalue);
}
function Trim (str) {
if (str==null) return "";
if (str.length==0) return "";
var i=0,j=str.length-1,c;
for (; i<str.length;i++) {
C=str.charat (i);
if (c!= ') break;
}
for (; j>-1;j--) {
C=str.charat (j);
if (c!= ') break;
}
if (i>j) return "";
Return str.substring (i,j+1);
}
function Validatedate (date,format,alt) {
var Time=trim (Date.Value);
if (time== "") return;
var Reg=format;
var reg=reg.replace (/yyyy/, "[0-9]{4}");
var reg=reg.replace (/yy/, "[0-9]{2}");
var reg=reg.replace (/mm/, "((0[1-9)) |1[0-2]");
var reg=reg.replace (/m/, "(([1-9]) |1[0-2])");
var reg=reg.replace (/dd/, "(0[1-9)) | ( [1-2] [0-9]) | 30|31) ");
var reg=reg.replace (/d/, "[1-9]|[ 1-2][0-9]|30|31));
var reg=reg.replace (/hh/, "([[0-1][0-9]) |20|21|22|23)");
var reg=reg.replace (/h/, "([0-9]|1[0-9]|20|21|22|23)");
var reg=reg.replace (/mm/, "([0-5][0-9])");
var reg=reg.replace (/m/, "[0-9]| ( [1-5] [0-9]));
var reg=reg.replace (/ss/, "([0-5][0-9])");
var reg=reg.replace (/s/, "[0-9]| ( [1-5] [0-9]));
Reg=new RegExp ("^" +reg+ "$");
if (Reg.test (time) ==false) {//Verify that the format is legitimate
Alert (ALT);
Date.focus ();
return false;
}
return true;
}
function Validatedategroup (year,month,day,alt) {
var array=new array (31,28,31,30,31,30,31,31,30,31,30,31);
var y=parseint (Year.value);
var m=parseint (Month.value);
var d=parseint (Day.value);
var maxday=array[m-1];
if (m==2) {
if ((y%4==0&&y%100!=0) | | y%400==0) {
maxday=29;
}
}
if (d>maxday) {
Alert (ALT);
return false;
}
return true;
}
function Validatecheckbox (obj,alt) {
var Rs=false;
if (obj!=null) {
if (obj.length==null) {
return obj.checked;
}
for (i=0;i<obj.length;i++) {
if (obj[i].checked==true) {
return true;
}
}
}
Alert (ALT);
Return RS;
}
function Validateradio (obj,alt) {
var Rs=false;
if (obj!=null) {
if (obj.length==null) {
return obj.checked;
}
for (i=0;i<obj.length;i++) {
if (obj[i].checked==true) {
return true;
}
}
}
Alert (ALT);
Return RS;
}
function Validateselect (obj,alt) {
var Rs=false;
if (obj!=null) {
for (i=0;i<obj.options.length;i++) {
if (obj.options[i].selected==true) {
return true;
}
}
}
Alert (ALT);
Return RS;
}
function Validateemail (email,alt,separator) {
var Mail=trim (Email.value);
if (mail== "") return;
var em;
var myreg =/^[_a-z0-9]+@ ([_a-z0-9]+\.) +[a-z0-9]{2,3}$/;
if (separator==null) {
if (Myreg.test (email.value) ==false) {
Alert (ALT);
Email.focus ();
return false;
}
}
else{
Em=email.value.split (separator);
for (i=0;i<em.length;i++) {
Em[i]=em[i].trim ();
if (Em[i].length>0&&myreg.test (Em[i]) ==false) {
Alert (ALT);
Email.focus ();
return false;
}
}
}
return true;
}
function Validateform (theform) {//returns TRUE if validation passes
var disablelist=new Array ();
var field = theform.elements; Put all the elements in a form into an array
for (var i = 0; i < field.length; i++) {
var vali=theform.validate;
if (vali!=null) {
if (vali.value== "0") {
var fun=vali.functionname;
if (fun!=null) {
Return eval (fun+ "()");
}
else{
return true;
}
}
}
var Empty=false;
var Value=trim (Field[i].value);
if (value.length==0) {//IS null value
Empty=true;
}
var emptyinfo=field[i].emptyinfo;//null value Verification
if (emptyinfo!=null&&empty==true) {
alert (emptyinfo);
Field[i].focus ();
return false;
}
Maximum length verification for Var lengthinfo=field[i].lengthinfo;//
if (lengthinfo!=null&&getstringlength (value) >field[i].maxlength) {
alert (lengthinfo);
Field[i].focus ();
return false;
}
var Validatortype=field[i].validatortype;
if (validatortype!=null) {//other JavaScript
var rs=true;
if (validatortype== "JavaScript") {
Eval ("rs=" +field[i].functionname+ "()");
if (Rs==false) {
return false;
}
else{
Continue
}
}
else if (validatortype== "Disable") {//button for disable before submitting form
disablelist.length++;
Disablelist[disablelist.length-1]=field[i];
Continue
}
else if (validatortype== "Date") {
Rs=validatedate (Theform.elements (field[i].fieldname), field[i].format,field[i].errorinfo);
}
else if (validatortype== "Dategroup") {
Rs=validatedategroup (Theform.elements (field[i].year), theform.elements (Field[i].month), theForm.elements (field[i ].day), field[i].errorinfo);
}
else if (validatortype== "Checkbox") {
Rs=validatecheckbox (Theform.elements (field[i].fieldname), field[i].errorinfo);
}
else if (validatortype== "Radio") {
Rs=validateradio (Theform.elements (field[i].fieldname), field[i].errorinfo);
}
else if (validatortype== "Select") {
Rs=validateselect (Theform.elements (field[i].fieldname), field[i].errorinfo);
}
else if (validatortype== "Email") {
Rs=validateemail (Theform.elements (field[i].fieldname), field[i].errorinfo);
}
else{
Alert ("Authentication type is not supported, FieldName:" +field[i].name);
return false;
}
if (Rs==false) {
return false;
}
}
else{//General Verification
if (Empty==false) {
var v = field[i].validator; Gets its Validator property
if (!V) continue; If the property does not exist, ignore the current element
var reg=new RegExp (v);
if (Reg.test (field[i].value) ==false) {
alert (field[i].errorinfo);
Field[i].focus ();
return false;
}
}
}
}
for (i=0;i<disablelist.length;i++) {
Disablelist[i].disabled=true;
}
return true;
}
</script>