Regular Expression learning-Reprint-2 good... -ASP. NET

Source: Internet
Author: User

The group in the regular expression is very Nb
Tan zhenlin's regular expression series explain well!

Original post: Garden of the http://tuantuan.cnblogs.com/articles/416806.html Group

The Prime Minister talked about Regexp, the regular expression object of JScript.
The class that provides regular expression operations in JScript is called Regexp. You can instantiate Regexp objects in two ways.
Method 1: constructor instantiation:
VaR myregex = new Regexp ("// W +", "IgM ");
/// W + indicates the actual regular expression. Note that the first regular expression is used for escape.
IgM indicates case-insensitive, global search, and multi-row search (usually m by default)

Method 2: Direct Value assignment:
VaR myregex = // W +/IgM;
The effect of/regular expression/IGM is the same as that of the previous statement, but there is no need to use transfer characters here. The original regular expression is what it looks like, and the role of IgM is the same as that of the previous example.
I personally think that regular expressions written in the second method are easier to read. The regexbuddy help document also recommends the second method.
The Regexp object contains the following operations:
Exec (string Str): Execute Regular Expression matching and return matching results. According to the running result of the msdn example, every execution of exec starts from the end position of the previous direct match, in addition, the returned value seems to be an rerexp object, while regexbuddy returns an array but does not provide a detailed example. I think it is more reliable Based on the test results.

Compile (string RegEx, string flags): Pre-compiled regular expressions to run faster. After testing, the efficiency is significantly improved after pre-compilation. The RegEx parameter is a regular expression, and flags can be a combination of the following three values: G-global search, my test results show that only the first matching string can be matched without the G sign. I-ignore case-insensitive M-multi-row search. It seems that multi-row search is already performed by default.
Test (string Str): returns true if STR matches the regular expression; otherwise, returns false, which is similar to the match method of the string object.
The Regexp object contains the following attributes:
Index: the position of the First Matching expression in the string, initially-1
Input: match the target of the regular expression. Note that it is read-only.
Lastindex: the position of the next matching expression. The original statement is (returns the character position where the next match begins in a searched string.). I do not know whether there is a translation error. I have not used this attribute.
Lastmatch: string of the last matching expression
Lastparen: The last matched sub-match string. For example, a regular expression contains multiple matching items grouped by (). lastparen indicates the matching result of the last group.
Leftcontext: All characters starting from the start of the target string to the start position of last match.
Rightcontext: All characters from the end position of last match to the end position of the entire target string.
$1... $9: indicates the matching result of group N. This is useful when multiple groups in the regular expression are grouped ().
Next, let's talk about the operations related to the regular expression of the string object in JScript:
Match (string RegEx): accepts a regular expression and returns whether the string matches the regular expression.
Replace (srting RegEx, string Str): replace the substring that matches the regular expression with Str. This function seems simple, but it also hides more advanced usage. See the following example.
Example 1:
VaR str1 = "A: My name is Peter! /NB: Hi Peter! ";
Str1 = str1.replace (/Peter/g, "Jack ");
Alert (str1 );
In this example, the string is replaced. The power of this expression is certainly not limited to this. If you are skilled, you can use it to do a lot of work that previously required a lot of code. For example, add the highlighted HTML tag before and after the code keyword. From the previous example, it seems that replace can only replace the matched text with the new text. How can we use it to insert tags before and after keywords? As you can imagine, if you can use the matching results when you replace them, you just need to replace the keyword with: Tag header + keyword + tag tail.
But how can we use regular expression matching results in replace?
In this case, we need to use the "matching variable". The matching variable is used to represent the result of regular expression matching. The following describes the matching variables:
$ & -- Indicates the matching results of all matching groups. The matching group is the () Group of the regular expression.
$ -- Represents $ characters. Because $ characters are used for matching variables, escape
$ N -- similar to the previous $1... $9 indicates the result of group N matching
$ NN -- the result of the NN group match is very simple.
$ '-- The leftcontext mentioned above. For example, if abcdefg is matched with D, ABC is its leftcontext.
$ '-- It is very close to the above and should not be mistaken !, This is rightcontext. EFG is the rightcontext in the above example. Now we need to insert tags before and after keywords:
VaR str1 = "A: My name is Peter! /NB: Hi Peter! ";
Str1 = str1.replace (/Peter/g ,"$ &");
Alert (str1 );
All 0: 39... Write it here.
Download the regular expression tool software (password: RegEx): RegEx buddy 2.06.zip
For examples I have written, see JScript syntax highlighting (simplified code)

Here are some examples of msdn:
Function matchdemo ()
{
VaR S;
VaR Re = new Regexp ("d (B +) (D)", "ig ");
VaR STR = "cdbbdbsbdbdz ";
VaR arr = re.exe C (STR );
S = "$1 contains:" + Regexp. $1 + "/N ";
S + = "$2 contains:" + Regexp. $2 + "/N ";
S + = "$3 contains:" + Regexp. $3;
Return (s );
}
Function regexptest ()
{
VaR ver = Number (scriptenginemajorversion () + "." + scriptengineminorversion ())
If (ver >=5.5 ){
VaR src = "The rain in Spain falls mainly in the plain .";
VaR Re = // W +/g;
VaR arr;
While (ARR = re.exe C (SRC ))! = NULL)
Print (ARR. index + "-" + arr. lastindex + "/t" + ARR );
}
Else {
Alert ("You need a newer version of JScript for this to work ");
}
}
Function matchdemo ()
{
VaR s; // declare variable.
VaR Re = new Regexp ("d (B +) (D)", "ig"); // regular expression pattern.
VaR STR = "cdbbdbsbdbdz"; // string to be searched.
VaR arr = re.exe C (STR); // perform the search.
S = "$1 returns:" + Regexp. $1 + "/N ";
S + = "$2 returns:" + Regexp. $2 + "/N ";
S + = "$3 returns:" + Regexp. $3 + "/N ";
S + = "input returns:" + Regexp. Input + "/N ";
S + = "lastmatch returns:" + Regexp. lastmatch + "/N ";
S + = "leftcontext returns:" + Regexp. leftcontext + "/N ";
S + = "rightcontext returns:" + Regexp. rightcontext + "/N ";
S + = "lastparen returns:" + Regexp. lastparen + "/N ";
Return (s); // return results.
}
Document. Write (matchdemo ());

Original post: http://blog.csdn.net/duduwolf/archive/2004/08/21/80825.aspx

The regular expression is a regular expression. It seems that English is better understood than Chinese, that is, checking expression characters
Not compliant !! Regular expressions have a very powerful and complex object Regexp. In javascript1.2
.
Let's take a look at the introduction of regular expressions:
The regular expression object is used to regulate a standard expression (that is, the expression operator does not meet specific requirements, such as whether it is an email
It has the attributes and methods used to check whether the given string meets the rules.
In addition, the attributes of individual regular expression objects created by using the Regexp constructor have been pre-defined.
You can use static attributes of objects at any time.
Core objects:
Available in Javascript 1.2 and NES 3.0 and later versions.
The tosource method is added in Versions later than JavaScript 1.3.
Creation method:
Text format or Regexp constructor function.
The text format is as follows:
/Pattern/flags:/mode/flag
The constructor function method is as follows:
New Regexp ("pattern" [, "Flags"]) is new Regexp ("Mode" [, "flag"])
Parameters:
Pattern)
Indicates the text of a regular expression.
Flags)
If this option is specified, flags can be one of the following nominal values:
G: Global match (exact match)
I: Ignore case (case insensitive)
GI: both global match and ignore case (matching all possible values, Case Insensitive)
Note: Do not Mark parameters in text format with quotation marks, while parameters in constructors must be marked with quotation marks. So the following
The expression creates the same regular expression:
/AB + C/I
New Regexp ("AB + C", "I ")
Description:
When using constructor, you must use a normal string to avoid rules (adding leading characters/To strings.
For example, the following two statements are equivalent:
Re = new Regexp ("// W + ")
Re = // W +/
The following provides a complete list and description of special characters that can be used in regular expressions.
Table 1.3: special characters in Regular Expressions:
Character/
Meaning: For characters, it usually indicates the literal meaning, indicating that the subsequent characters are special characters, and/is not interpreted.
For example, if/B/matches the character 'B', add a backslash (/) before B, that is, // B/, then the character becomes a special character, indicating
Match the dividing line of a word.
Or:
For a few characters, it is generally described as special. It is pointed out that the subsequent characters are not special, but should be interpreted literally.
For example, * is a special character that matches any character (including 0 characters). For example,/a */indicates that it matches 0 or multiple A characters.
To match the literal *, add a backslash before a. For example,/a/*/matches 'A *'.
Character ^
Meaning: The matched characters must be at the frontend.
For example,/^ A/does not match 'A' in "an A,", but matches 'A' in the top of "an '.
Character $
Meaning: similar to ^, it matches the last character.
For example,/t $/does not match 'T' in "Eater", but matches 'T' in "eat '.
Character *
Meaning: match the first character of * 0 or N times.
For example,/Bo */matches 'boooo' in "A ghost booooed" or 'B' in "A bird warbled", but does not match "a goat g
Any character in runted.
Character +
Meaning: match the character before the plus sign once or N times. It is equivalent to {1 ,}.
For example,/a +/matches all 'A' in "Candy" and "caaaaaaandy '.
Character?
Meaning: match? The first character is 0 or 1 time.
Example:/e? Le? /Match 'El' in "angel" and 'le' in "angle '.
Character.
Meaning: (decimal point) match all single characters except line breaks.
For example,/. N/matches 'any' and 'on' in "Nay, an apple is on the tree", but does not match 'nay '.

Character (X)
Meaning: Match 'X' and record the matched value.
For example,/(FOO)/matches and records 'foo' in "foo bar '. Matching substrings can be returned by the element [1],..., [N] In the result array.
Returned by Regexp object attributes $1,..., $9.
Character X | y
Meaning: Match 'X' or 'y '.
For example,/green | red/matches 'green' in "green apple" and 'red' in "red apple '.
Character {n}
Meaning: Here N is a positive integer. Match the previous n characters.
For example:/a {2}/does not match 'A' in "Candy,", but matches all 'A' in "caandy," and the first two in "caaandy ."
'A '.
Character {n ,}
Meaning: Here N is a positive integer. Match at least n first characters.
For example,/a {2,} does not match 'A' in "Candy", but matches all 'A' in "caandy" and "caaaaaaandy'
Character {n, m}
Meaning: both N and m are positive integers. Match at least n characters at most before M.
For example,/a {}/does not match any character in "cndy", but matches the first two characters in "Candy," 'A', "caandy ,"
'A' and "caaaaaaandy" are the first three 'A'. Note: Even if "caaaaaaandy" contains many 'A', it only matches the first three.
(Aaa ".
Character [xyz]
Meaning: A one-character list that matches any character in the list. You can use a hyphen to indicate a character range.
For example, [ABCD] is the same as [A-C. They match 'B' in "brisket" and 'C' in "ache '.
Character [^ XYZ]
Meaning: A character complement, that is, it matches everything except the listed characters. You can use a hyphen to indicate
Character range.
For example, [^ ABC] is equivalent to [^ A-C]. They first match 'R' in "brisket" and 'H' in "chop '.
Character [/B]
Meaning: match a space (do not confuse with/B)
Character/B
Meaning: match the boundary of a word, such as a space (do not confuse it with [/B)
For example, // BN/W/matches 'no' in "noonday", // WY/B/matches 'ly 'in "possibly yesterday '.
Character/B
Meaning: match the non-dividing line of a word
For example: // w/BN/match 'on' in "noonday",/y/B/W/match 'Ye 'in "possibly yesterday '.
Character/CX
Meaning: X is a control character. Matches the control character of a string.
For example, // cm/matches control-m in a string.
Character/d
Meaning: matching a number is equivalent to [0-9].
For example, // D/or/[0-9]/matches '2' in "B2 is the suite number '.
Character/d
Meaning: match any non-number, which is equivalent to [^ 0-9].
For example, // D/or [^ 0-9]/matches 'B' in "B2 is the suite number '.
Character/F
Meaning: match a form character
Character/n
Meaning: match a linefeed.
Character/R
Meaning: match a carriage return.
Character/s
Meaning: match a single white space character, including space, tab, form feed, line feed, equivalent to [/f/n/R/T/V].
For example, // S/W */matches 'bar' in "foo bar '.
Character/s
Meaning: match a single character except the white space character, which is equivalent to [^/f/n/R/T/V].
For example, // S // w * matches 'foo' in "foo bar '.
Character/T
Meaning: match a tab
Character/V
Meaning: match a top Tab
Character/W
Meaning: match all numbers, letters, and underscores, equivalent to [A-Za-z0-9 _].
For example: // w/match 'A' in "apple,", "$5.28,", "5", and "3D '.
Character/W
Meaning: match other characters except numbers, letters, and underscores, equivalent to [^ A-Za-z0-9 _].
For example: // w/or/[^ $ A-Za-z0-9 _]/matches '%' in "50% '.
Character/n
Meaning: Here N is a positive integer. Match the N value of the last substring of a regular expression (left parentheses ).
For example:/Apple (,)/sorange/1/match 'apple, orange, cherry, Peach. ".
There is a more complete example.
Note: If the number in the left parentheses is smaller than the number specified by/N,/n removes the octal escape of a row as the description.
Character/ooctal and/xhex
Meaning: Here/ooctal is an escape value of octal, And/xhex is a hexadecimal escape value, which can be
An ASCII code is embedded in a regular expression.

When the expression is checked, the text symbol provides the method to edit the regular expression. Use text symbols to make regular expressions
The formula is constant. For example, if you use text symbols in a loop to construct a regular expression
Compile multiple times.
Regular Expression object constructor, for example, new Regexp ("AB + C"), provides runtime compilation for regular expressions. When you know
When the expression pattern changes, you should use the constructor, or you do not know the pattern of the regular expression.
When the source is obtained, such as when the user inputs. Once you have defined a regular expression, it can be used anywhere,
It can also be changed. You can use the compilation method to compile a new regular expression for reuse.
A separated pre-defined Regexp object can be used in each window; that is, each separated JavaScript thread runs
To obtain the Regexp object. Because each script cannot be interrupted in a thread, this ensures that different scripts will not be overwritten.
The value of the Regexp object.
Predefined static attributes of a Regexp object: input, multiline, lastmatch, lastparen, leftcontext,
Rightcontext, and from $1 to $9. The input and Multiline attributes can be preset. The values of other static attributes are executing individual regular expressions.
After the exec and test methods of the expression object, and set after the string match and replace methods are executed.
Attribute
Note that several attributes of the Regexp object have both long names and short names (such as Perl ). These names all point to the same value. Perl is
A programming language, while JavaScript imitates its regular expression.
Attribute $1,..., $9
Obtain matched substrings, if any.
Attribute $ _
Reference Input
Attribute $ *
See multiline
Attribute $ &
Refer to lastmatch
Attribute $ +
Refer to lastparen
Attribute $'
Refer to leftcontext
Attribute $'
Refer to rightcontext
Attribute Constructor
Specify the object prototype Function
Attribute global
Determines whether to test whether the regular expression cannot match all strings or only conflicts with the first one.
Attribute ignorecase
Determines whether to ignore the case sensitivity when trying to match a string
Attribute Input
When the regular expression is matched, it is the opposite string.
Property lastindex
Determine where the next match starts
Attribute lastmatch
Last matched character
Property lastparen
The last parenthesized when the substring is matched, if any.
Attribute leftcontext
The substring before the last match.
Attribute multiline
Whether to search for strings in multiple rows.
Attribute prototype
Allow attributes to be appended to all objects
Attribute rightcontext
The substring after the last match.
Attribute source
Mode text

Method
Compile Method
Compile a regular expression object
Exec Method
Run regular expression matching
Test Method
Test Regular Expression matching
Tosource Method
Returns the text description of an object. You can use this value to create a new object. Ignore object. TOS
Ource method.
Tostring Method
Returns a string that describes the specified object, regardless of the object. tostring object.
Valueof Method
Returns the original value of the specified diagonal. The object. valueof method is not considered.
In addition, this object inherits the watch and unwatch methods of the object.

Example:
Example 1: The following sample script uses the replace method to convert words in a string. In the replaced text, the script uses the Global Regexp
The value of the $1 and $2 attributes of the object. Note: When passed as the second parameter to the replace method, the $ attribute name of the Regexp object
Name.

Result: "Smith, John ".
Example 2: In the following sample script, Regexp. input is set by the change event processing handle. In the getinfo function, the exec Method
Use the value of Regexp. input as its parameter. Note that Regexp has a $ attribute preset.


Enter your surname and age, and press Enter.
  

  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.