Http://www.jb51.net/article/25313.htm
Regular expressions can:
• Test a pattern for a string. For example, you can test an input string to see if there is a phone number pattern or a credit card number pattern in the string. This is called data validation
• Replace text. You can use a regular expression in your document to identify specific text, and then you can either delete it all or replace it with another text
• Extracts a substring from a string based on pattern matching. Can be used to find specific text in text or input fields
Regular expression syntax
A regular expression is a text pattern consisting of ordinary characters, such as characters A through z, and special characters (called metacharacters). This pattern describes one or more strings to match when looking up a text body. A regular expression, as a template, matches a character pattern to the string you are searching for.
To create a regular expression
Copy CodeThe code is as follows:
var re = new RegExp ();//regexp is an object, just like Aarray
However, this has no effect and requires the content of the regular expression to be passed in as a string.
Re =new REGEXP ("a");//The simplest regular expression that will match the letter A
Re=new RegExp ("A", "I");//The second parameter, which indicates that the match is not case-sensitive
RegExp constructor The first argument is the text content of a regular expression, and the first parameter is an optional flag. Flags can be combined with
• G (Full-text search)
• I (ignoring case)
• m (Multi-line lookup)
Copy CodeThe code is as follows:
var re = new RegExp ("A", "GI");//matches all A or a
Regular expressions There is another way to declare a regular expression literal
Copy CodeThe code is as follows:
var re =/a/gi;
Regular expression-related methods and properties
Methods for regular Expression objects
test, which returns a Boolean value that indicates whether a pattern exists in the string being looked up. Returns true if it exists, or false if it is present.
exec, runs the lookup in a string with the regular expression pattern, and returns the package <script type= "Text/javascript" src= "http://www.javaeye.com/javascripts/tinymce/ Themes/advanced/langs/zh.js "></script><script type=" Text/javascript "src=" http://www.javaeye.com/ Javascripts/tinymce/plugins/javaeye/langs/zh.js "></script> An array with the result of the lookup.
compile, the regular expression is compiled into an internal format, which executes faster.
The properties of the regular Expression object
A source that returns a copy of the text of the regular expression pattern. Read-only.
lastindex, which returns the position of the character, which is the beginning of the next successful match for the found string.
$1...$9, returns nine of the most recently saved parts found during pattern matching. Read-only.
input ($_), which returns the string that executes the canonical expression lookup. Read-only.
Lastmatch ($&) that returns the last matching character in any regular expression search process. Read-only.
Lastparen ($+), if any, returns the last sub-match during any regular expression lookup. Read-only.
leftcontext ($ ') that returns the character from the beginning of the string in the searched string to the position before the last match. Read-only.
rightcontext ($ '), returns the character from the last matching position in the searched string to the end of the string. Read-only.
String object Some methods related to regular expressions
match, finds a match for one or more regular expressions.
Replace, replacing the substring that matches the regular expression.
Search, retrieves the value that matches the regular expression.
split, splits the string into an array of strings.
Test how regular expressions work!
Copy CodeThe code is as follows:
The test method, which tests the string, returns True when conforming to the pattern, otherwise returns false
var re =/he/;//The simplest regular expression that will match the word "he"
var str = "he";
Alert (Re.test (str));//true
str = "we";
Alert (Re.test (str));//false
str = "HE";
Alert (Re.test (str));//false, uppercase, if you want to match case, you can specify I flag (i is the representation of ignorecase or case-insensitive)
re =/he/i;
Alert (Re.test (str));//true
str = "certainly! He loves her! ";
Alert (Re.test (str));//true, as long as the He (he) is included, if it is only he or he, there can be no other characters, you can use ^ and $
Re =/^he/i;//Caret (^) represents the start position of the character
Alert (Re.test (str));//false, because he is not at the beginning of str
str = "He is a good boy!";
Alert (Re.test (str));//true,he is the starting position of the character, and you need to use the $
Re =/^he$/i;//$ indicates the end position of the character
Alert (Re.test (str));//false
str = "He";
Alert (Re.test (str));//true
Of course, it's not possible to find out how powerful regular expressions are because we can use = = or indexof in the example above.
Re =/\s/;//\s matches any white space character, including spaces, tabs, page breaks, and so on
str= "user name";//username contains spaces
Alert (Re.test (str));//true
str = "user name";//Username contains tabs
Alert (Re.test (str));//true
Re=/^[a-z]/i;//[] matches any character in the specified range, this will match the English letter, not case sensitive
Str= "VariableName";//variable names must start with a letter
Alert (Re.test (str));//true
Str= "123ABC";
Alert (Re.test (str));//false
Of course, it's not enough to just know if a string matches the pattern, and we need to know which characters match the pattern.
Copy CodeThe code is as follows:
var osVersion = "Ubuntu 8";//8 of which represents the system major version number
var re =/^[a-z]+\s+\d+$/i; The + sign indicates that the character must appear at least 1 times, \s represents a white space character, and \d represents a number
Alert (Re.test (osVersion));//true, but we'd like to know the main version number
Another method, exec, returns an array with the first element of the array as the complete match
re=/^[a-z]+\s+\d+$/i;
arr = re.exec (osVersion);
Alert (arr[0]);//Will osversion the full output, because the entire string exactly matches the re
I just need to take out the numbers.
re=/\d+/;
var arr = re.exec (osVersion);
Alert (arr[0]);//8
More complex usage, using sub-matching
Copy CodeThe code is as follows:
The 1th to n elements of the array returned by exec contain any one of the sub-matches appearing in the match
re=/^[a-z]+\s+ (\d+) $/i;//use () to create a sub-match
Arr =re.exec (osVersion);
Alert (arr[0]);//The entire osversion, which is the complete match of the regular expression
Alert (arr[1]);//8, the first sub-match, the fact that you can also remove the major version number
alert (arr.length);//2
OsVersion = "Ubuntu 8.10";//Remove Major and minor version numbers
Re =/^[a-z]+\s+ (\d+) \. (\d+) $/i;//. is one of the regular expression metacharacters to be escaped with its literal meaning
arr = re.exec (osVersion);
Alert (arr[0]);//Complete OSVersion
Alert (arr[1]);//8
Alert (arr[2]);//10
Note that when the string does not match the RE, the Exec method returns null
Some methods of the string object related to regular expressions
Copy CodeThe code is as follows:
Replace method, for replacing strings
var str = "some money";
Alert (Str.replace ("some", "much"));//much money
The first parameter of replace can be a regular expression
var re =/\s/;//whitespace character
Alert (Str.replace (Re, "%"));//some%money
Regular expressions are extremely handy when you don't know how many white space characters are in a string
str = "some some \tsome\t\f";
re =/\s+/;
Alert (Str.replace (Re, "#"));//But this will only replace the first occurrence of a bunch of blank characters
Because a regular expression can only match once, \s+ matches the first space and exits.
Re =/\s+/g;//g, global flag, will make regular expression match entire string
Alert (Str.replace (Re, "@"));//[email Protected]@[email protected]
var str = "ADF9DF9DF9",//the string in the text file;
Re =/9/gi,//Match 9
Counter = 0; Counter var newstr =
str = str.replace (Re, function () {
counter++; Each time a match occurs, the function is executed once, and the return value of the function is used to replace the original value
Return "#";
});
Alert ("Number of Replacements:" +counter);
alert (str);
Finally Str becomes adf#df#df# "
var str = "He is 22 years old, she is 20 years old, his father is 45 years old, her father this year 44 years old, a total of 4 people"
function Test ($) {
var gyear = (new Date ()). GetYear ()-parseint ($) + 1;
return $ + "(" + Gyear + "Year of birth)";
}
var reg = new RegExp ("(http://www.cnblogs.com/sgivee/admin/file://d/+) years old", "G");
var reg =/(\d+) old/gi;
var newstr = str.replace (reg, test);
alert (str);
alert (NEWSTR);
Another similarity is split.
var str = "A-bd-c";
var arr = str.split ("-");//Return ["A", "BD", "C"]
If STR is entered by the user, he may enter A-bd-c or a BD C or A_bd_c, but it will not be ABDC (that is, he loses the wrong)
str = "A_DB-C";//Users add separators in the way he likes
re=/[^a-z]/i;//Front We say ^ means the character starts, but in [] it represents a negative character set
Matches any character that is not within the specified range, where all characters except the letter are matched
arr = Str.split (re);//Still returns ["a", "BD", "C"];
When looking in a string, we often use indexof, which corresponds to the search method used for regular lookups.
str = "My age is 18.Golden age!"; /age is not certain, we can't find its location with indexof
re =/\d+/;
Alert (Str.search (re));//Returns the string that is found to start subscript 10
Note that because the lookup itself is the first time it returns immediately, you do not need to use the G flag in search
Although the following code is not an error, the G flag is superfluous
re=/\d+/g;
Alert (Str.search (re));//Still 10
Similar to the Exec method, the match method of a string object is also used to match a string to a regular expression and return an array of results
Copy CodeThe code is as follows:
var str = "My name is CJ." Hello everyone! ";
var re =/[a-z]/;//matches all uppercase letters
var arr = Str.match (re);//return array
Alert (arr);//The array will only contain one m because we do not use global match
re =/[a-z]/g;
arr = Str.match (re);
Alert (arr);//m,c,j,h
Extracting words from a string
Re =/\b[a-z]*\b/gi;//\b denotes word boundaries
str = "one three four";
Alert (Str.match (re));//one,two,three,four
RegExp Some properties of an object instance
Copy CodeThe code is as follows:
var re =/[a-z]/i;
alert (re.source);//Output [A-z] string
Note that the direct alert (re) outputs the regular expression along with the forward slash and flag, which is defined by the Re.tostring method.
var re =/[a-z]/i;
alert (Re.source);
Output A [A-z] string
Note that the direct alert (re) outputs the regular expression along with the forward slash and flag, which is defined by the Re.tostring method.
An instance of each RegExp object has a lastindex property, which is the starting position of the next successful match for the found string, and the default value is-1. The LastIndex property is modified by the exec and test methods of the RegExp object. And it is writable.
Copy CodeThe code is as follows:
var re =/[a-z]/;
After the Exec method executes, the Lastindex property of the RE is modified,
var str = "Hello,world!!!";
var arr = re.exec (str);
alert (re.lastindex);//0 because the global flag is not set
re =/[a-z]/g;
arr = re.exec (str);
alert (re.lastindex);//1
arr = re.exec (str);
alert (re.lastindex);//7
When the match fails (there is no match later), or if the lastindex value is greater than the string length, the Exec method will set lastindex to 0 (start position)
Copy CodeThe code is as follows:
var re =/[a-z]/;
var str = "Hello,world!!!";
Re.lastindex = 120;
var arr = re.exec (str);
alert (re.lastindex);//0
Static properties of the RegExp object
Copy CodeThe code is as follows:
Input is finally used to match the string (the string passed to the Test,exec method)
var re =/[a-z]/;
var str = "Hello,world!!!";
var arr = re.exec (str);
alert (regexp.input);//hello,world!!!
Re.exec ("TempStr");
alert (regexp.input);//is still hello,world!!!, because TempStr does not match
Lastmatch last-match characters
re =/[a-z]/g;
str = "HI";
Re.test (str);
alert (regexp.lastmatch);//h
Re.test (str);
Alert (regexp["$&"]),//i,$& is the short name of Lastmatch, but because it is not a valid variable name, it is.
Lastparen Last matching grouping
Re =/[a-z] (\d+)/gi;
str = "Class1 Class2 Class3";
Re.test (str);
alert (regexp.lastparen);//1
Re.test (str);
Alert (regexp["$+"]);//2
Leftcontext returns the character from the beginning of the string in the searched string to the position before the last match
Rigthcontext returns the character from the last matching position in the searched string to the end of the string
re =/[a-z]/g;
str = "123abc456";
Re.test (str);
alert (regexp.leftcontext);//123
alert (regexp.rightcontext);//bc456
Re.test (str);
Alert (regexp["$ '"]);//123a
Alert (regexp["$ '"]);//c456
The Multiline property returns whether the regular expression uses multiline mode, which is not for a regular expression instance, but for all regular expressions, and this property is writable. (IE and opera do not support this attribute)
Copy CodeThe code is as follows:
alert (regexp.multiline);
Because Ie,opera does not support this property, it is best to specify it separately
var re =/\w+/m;
alert (re.multiline);
Alert (regexp["$*"]); static properties of//regexp objects do not change because the m flag is specified for an object instance of REGEXP
Regexp.multiline = true;//This will open the multiline matching pattern for all regular expression instances
alert (regexp.multiline);
Using metacharacters Note: Metacharacters are part of regular expressions and must be escaped when we want to match the regular expression itself. Here are all the metacharacters used by the regular expression
( [ { \ ^ $ | ) ? * + .
Copy CodeThe code is as follows:
var str = "?";
var re =/?/;
Alert (Re.test (str));//error, because? is a meta character and must be escaped
re =/\?/;
Alert (Re.test (str));//true
Use the RegExp constructor with the regular expression literal to create a regular expression note point
Copy CodeThe code is as follows:
var str = "\?";
alert (str);//Output only?
var re =/\?/;//will match?
Alert (Re.test (str));//true
Re = new RegExp ("\?"); /error because this is equivalent to re =/\?/
Re = new RegExp ("\ \"); /correct, will match?
Alert (Re.test (str));//true
Since double escaping is so unfriendly, it is still declared with regular expression literals.
How do I use special characters in regular expressions?
Copy CodeThe code is as follows:
ASCII means special characters in hexadecimal numbers
var re =/^\x43\x4a$/;//will match CJ
Alert (Re.test ("CJ"));//true
You can also use the Octal method
Re =/^\103\112$/;//will match CJ
Alert (Re.test ("CJ"));//true
You can also use Unicode encoding
Re =/^\u0043\u004a$/;//uses Unicode, must start with u, followed by a four-bit 16-in representation of character encoding
Alert (Re.test ("CJ"));
Also, there are some other predefined special characters, as shown in the following table:
Character description
\ n line break
\ r return character
\ t tab
\f page Break (TAB)
\CX control characters corresponding to X
\b Backspace (BackSpace)
\v Vertical Tab
The ("") Null character ("")
Character class---Simple class, reverse class, scope class, combo class, predefined class
Copy CodeThe code is as follows:
Simple class
var re =/[abc123]/;//will match abc123 one of these 6 characters
Negative to Class
Re =/[^abc]/;//will match a character other than ABC
Scope class
Re =/[a-b]/;//will match lowercase a-b 26 letters
Re =/[^0-9]/;//will match one character in addition to 0-9 10 characters
Combination Class
Re =/[a-b0-9a-z_]/;//will match letters, numbers and underscores
The following is a predefined class in a regular expression
Code is equivalent to matching
. ie [^\n], other [^\n\r] matches any character except line break
\d [0-9] matching numbers
\d [^0-9] matches non-numeric characters
\s [\n\r\t\f\x0b] matches a white space character
\s [^ \n\r\t\f\x0b] matches a non-whitespace character
\w [a-za-z0-9_] matches alphanumeric and underscore
\w [^a-za-z0-9_] matches characters other than alphanumeric underscores
Quantifier (The following table quantifier is a greedy quantifier when a single occurrence)
Code description
* matches the preceding subexpression 0 or more times. For example, zo* can match "z" and "Zoo". * Equivalent to {0,}.
+ matches the preceding subexpression one or more times. For example, ' zo+ ' can match "Zo" and "Zoo", but not "Z". + equivalent to {1,}.
? Matches the preceding subexpression 0 or one time. For example, "Do (es)?" can match "do" in "do" or "does".? Equivalent to {0,1}.
{n} n is a non-negative integer. Matches the determined n times. For example, ' o{2} ' cannot match ' o ' in ' Bob ', but can match two o in ' food '.
{N,} n is a non-negative integer. Match at least n times. For example, ' o{2,} ' cannot match ' o ' in ' Bob ', but can match all o in ' Foooood '. ' O{1,} ' is equivalent to ' o+ '. ' O{0,} ' is equivalent to ' o* '.
{n,m} m and n are non-negative integers, where n <= m. Matches at least n times and matches up to M times. Liu, "o{1,3}" will match the first three o in "Fooooood". ' o{0,1} ' is equivalent to ' O? '. Note that there can be no spaces between a comma and two numbers.
Greedy quantifier and the lazy quantifier
• When matching with greedy quantifiers, it first treats the whole string as a match, if the match is exited, if it does not match, the last character is truncated, if it does not match, the last character is truncated to match until there is a match. Until now, we have come across quantifiers that are greedy quantifiers.
• When matching with an inert quantifier, it first treats the first character as a match, exits if successful, and if it fails, tests the first two characters and increments until a suitable match is encountered
The lazy quantifier only adds a "?" to the greedy quantifier. , such as "A +" is a greedy match, "A +?" It is inert.
Copy CodeThe code is as follows:
var str = "ABC";
var re =/\w+/;//will match ABC
Re =/\w+?/;//will match a
Multi-line mode
Copy CodeThe code is as follows:
var re =/[a-z]$/;
var str = "Ab\ncdef";
Alert (Str.replace (Re, "#"));//ab\ncde#
Re =/[a-z]$/m;
Alert (Str.replace (Re, "#"));//a#\ncde#
Grouping and non-capturing groups
Copy CodeThe code is as follows:
Re =/abc{2}/;//will match ABCC
Re =/(ABC) {2}/;//will match abcabc
All of the above groupings are capturing groups
str = "ABCABC # # #";
arr = re.exec (str);
Alert (arr[1]);//abc
Non-capturing groupings (?:)
Re =/(?: ABC) {2}/;
arr = re.exec (str);
Alert (arr[1]);//undefined
Candidate (that is, the "or")
Copy CodeThe code is as follows:
Re =/^a|bc$/;//will match the start position of a or the end position of the BC
str = "Add";
Alert (Re.test (str));//true
Re =/^ (A|BC) $/;//will match a or BC
str = "BC";
Alert (Re.test (str));//true
When a regular expression containing a grouping has been test,match,search these methods, each grouping is placed in a special place for future use, which is a special value in the grouping, which we call a reverse reference
JS Code
Copy CodeThe code is as follows:
var re =/(A? ( B? (C?))) /;
/* The regular expression above will produce three groupings in turn
A? B? (C?))) The most out of
B? (C?))
(C?) */
str = "ABC";
Re.test (str);//The reverse reference is stored in the static property $1-$9 of the RegExp object
Alert (regexp.$1+ "\ n" +regexp.$2+ "\ n" +regexp.$3);
A reverse reference can also be used in regular expressions using \1, \2 ... such forms of use
Re =/\d+ (\d) \d+\1\d+/;
str = "2008-1-1";
Alert (Re.test (str));//true
str = "2008-4_3";
Alert (Re.test (str));//false
You can use a reverse reference to require that the characters in a string must be the same. In addition, a special character sequence is used to represent a reverse reference in a method such as replace
JS Code
Copy CodeThe code is as follows:
Re =/(\d) \s (\d)/;
str = "1234 5678";
Alert (Str.replace (RE, "$ $"));//In this case, the first grouping 1234,$2 represents 5678
Other--〉 are forward-looking to capture characters that appear before a particular character, and only after the character is followed by a specific word characters to capture it. Negative forward-looking corresponding to forward-looking, which matches a character only when it is not followed by a specific character. When performing operations such as forward-looking and negative-looking, the regular expression engine pays attention to the parts that follow the string, but does not move the index
JS Code
Copy CodeThe code is as follows:
Forward Looking
Re =/([a-z]+ (? =\d))/I;
We're going to match a word followed by a number, and then return the word without returning a number.
str = "ABC every1 ABC";
Alert (Re.test (str));//true
alert (regexp.$1);//every
alert (re.lastindex);//The advantage of using foresight is that the forward-looking content (? =\d) is not considered a match, and the next match still starts with it
Negative forward looking (?!)
Re =/([A-z] (?! \d))/;i
Will match letters that do not contain numbers and will not return (?! \d) content in the
str = "ABC1 one";
Alert (Re.test (str));
alert (regexp.$1);//one
Build a regular expression that validates the validity of your e-mail address. e-mail address validity requirements (we would like to define): The user name can only contain alphanumeric and underscore, at least one bit, up to 25 bits, the user name immediately after the @, followed by the domain name, domain names can only contain alphanumeric and minus sign (-), and can not start or end with a minus sign, Then there is the domain suffix (there can be more than one), the domain name suffix must be dot number connected to 2-4 characters
JS Code
Copy CodeThe code is as follows:
var re =/^\w{1,15} (?: @ (?! -)) (?:(?: [a-z0-9-]*) (?: [A-z0-9] (?! -))(?:\. (?! -))) +[a-z]{2,4}$/; Articles you may be interested in:
- JS Common Regular Expression form validation code
- Using regular expressions to match nested HTML tags under java/js
- Regular expressions for filtering special characters in JS
- JS Replace function function, with regular expression to solve, JS replace all
- JS Limit text box can only enter a number (regular expression)
- Compare the regular expression of authentic verification mailbox JS code detailed
- Explanation of the test function of JS regular expression
- Useful JS Regular Expressions (mobile phone number/IP regular/ZIP/phone, etc.)
- A detailed description of the use of JS regular expressions
- JS can only enter regular expressions such as numbers or numbers and letters.
- JS Regular Expression Daquan (collation detailed and practical)
- JS verification phone number and phone support +86 regular expression
- JS Regular expression Validation numeric code
- JS Regular expression method for obtaining specific characters in a string
- JS Regular Expression Learning Note matching string
- The most detailed JS date in history regular expression sharing
- Summary of several usages of question marks in JS regular expressions
- JS Regular expression test () and exec () Usage instance
- JS Regular expression Matches digit letter underline, etc.
- Regular Expressions 30-minute introductory tutorial
- Common Regular Expressions
"Regular" proficient JS regular expression, not digest information is too large, good text