asp.net regular expressions for C # learning

Source: Internet
Author: User

ASP tutorials. NET C # learning regular expressions
I. Classification of groups
The groups in the regular group have capturing and non capture groups, and the capturing group is divided into normal capturing groups and named Capture groups, respectively
Capturing group: (exp)
Named Capture group: (? <name> exp)
Non-capture group: (?: EXP)

Ii. Role of the group
1, capturing the role of the group

The purpose of a capturing group is to save the contents of a regular expression exp match to a group for later use

such as a string:
<a href= "http://anmo./" title= "bed Waiting for You" > Csdn </a>
I want to get the URL, and it fits the rules in the <a...> tag, so you can do it

C # code
String test = "<a href=" http://anmo./"title=" bed Waiting for You ">csdn</a>";
Match m = regex.match (Test, @ "<as*href=" ([^ "]*)" "[^>]*>", regexoptions.ignorecase);
if (m.success)
MessageBox.Show (m.groups tutorial [1].value);

The above regular expression matches to the <a href= "http://anmo./" title= "bed Waiting for You" >, and we want the URL, the other part of the expression is only to ensure that the URL is in the <a...> tag, so the capturing group used here , save the matching URL to the capturing group, and then use M.groups[1].value to get what the capturing group matches.
M.groups[1].value is a reference to capture, and another way of referencing M.result ("$"), the effect is the same

A common capturing group is a reference to a capturing group using a natural number such as 1,2,3.
A named capturing group can refer to it directly by capturing the group's name without having to capture the sequence number of the group.

C # code
String test = "<a href=" http://anmo./"title=" bed Waiting for You ">csdn</a>";
Match m = regex.match (Test, @ "<as*href=" "(? <url>[^" "]*)" "[^>]*>", regexoptions.ignorecase);
if (m.success)
MessageBox.Show (m.groups["url"].value);


The group naming and ordinal collation of the capturing group is described later

2, the role of the non-capture group
The function of the non-capture group is two, the first is more common, the second one can understand

(1), Save system resources, improve efficiency
When using "¦" to represent "or" relationships, a slightly more complex situation requires () to limit the scope of "¦" Otherwise, the "¦" of the left and right sides of the overall "or" relationship, this is irrelevant, here is not explained in detail, but also useful {num} to expression matching times, sometimes in front also to use () Limiting the scope of action
While using () to limit the scope, by default, the matching results are saved to a capturing group, and most of the time, we do not need to save this part of the content, which has a certain side effects, waste system resources, reduce efficiency
One of the functions of a non-capture group is to eliminate this side effect, (?: exp) to match the rules represented by exp, but not to save matching results to a capturing group

such as matching hh:mm:ss time.

C # code
MessageBox.Show (Regex.IsMatch ("18:23:55", "^ (?: [01][0-9]|2[0-3])" (?:: [0-5][0-9]) {2}$ "). ToString ());

(?: [01][0-9]¦2[0-3]) verifies that the hours section conforms to the rule, but does not save the matching results to the capturing group
(?:: [0-5][0-9]) {2} verifies the seconds part but does not save the matching results to the capturing group
 
(2), when using the Regex.Split method, play the same function as the regexoptions. Explicitcapture parameter, this use is not much, understand on the line
 
Three, capturing group naming and ordinal ordering
The normal capture group is by "() the sequence of occurrences from left to right to the natural number 1,2,3 ... the named
named Capture Group is the (? <name> exp) named
 
But note that, in the event that the expression matches successfully, $ $ in any case represents what the entire expression matches, m.groups[0]. Value represents the content that the entire expression matches to, and can be abbreviated to M.value
 
In addition to the named Capture group, which can be referenced by name, it can also be referenced by ordinal, and its naming rule is to name the normal capturing group from left to right first, The named capture Group is then named from the beginning, left to right, for example
 
<as*href= "(? <url> [^"]*) "s*title=" ([^ "]*)" [^>]*> (? < text> [ss]*?] </a>
             2   url                   1                3    text
 

C # code
String test = "<a href=" http://anmo./"title=" bed Waiting for You ">csdn</a>";
Match m = regex.match (test, @ "<as*href=" "(? <url>[^" "]*)" "s*title=" ([^ "]*)" "[^>]*> (? <text>[ss]*?) </a> ", regexoptions.ignorecase);
if (m.success)
{
    richtextbox1.text + + = M.groups[0].value + "n";     & nbsp; //<a href= "http://anmo./" title= "bed Waiting for You" >CSDN</A>
    richTextBox1.Text = M.groups[1].value + "n";      //bed waiting for you
    richTextBox1.Text + + M.groups[2].value + "n";      //http://anmo.
    richTextBox1.Text + + + m.groups["url"].value + "n";  //http://anmo.
    richTextBox1.Text + + + M.groups[3].value + "n";      //csdn
& nbsp;   richTextBox1.Text + + + m.groups["text"].value + "n"; //csdn
}


Another way to refer to a group
In addition to the two references above M.groups[1].value and M.result ("$") for processing the result set, there is also a way of referencing in the case of substitution, as follows

Keep URL and link text only, remove other unwanted information from <a...> tags

C # code
String test = "<a href=" http://anmo./"title=" bed Waiting for You ">csdn</a>";
string result = Regex.Replace (Test, @ "<as*href=" ([^ "]*)" "s*title=" ([^ "]*)" "[^>]*> (? <text>[ss]*?) </a> ", @" <a href= "" $ "" >${text}</a> ", regexoptions.ignorecase);
MessageBox.Show (result);


The common capture group is referred to by $number, and named captures are referenced by ${name}


Pre-search
(? =exp)
(?! Exp
(? <=exp)
(? <!exp)

The following instructions are very easy to make people dizzy, without looking at it, I will in another way to explain their role and usage
(? =exp) match the position of the exp front
(? &LT;=EXP) matches the position of the exp rear
(?! EXP) match the position that follows not exp
(? &LT;!EXP) matches a position that is not exp at the front

Some of the data on the translation of zero-width assertion, I am accustomed to search this term, the first two for forward search, the latter two for reverse search, of course, there are other translations, is actually a meaning, know on the line, do not care

These four expressions, which are the same as non capture, do not save the matching results to the capturing group. The difference is that the content that is not captured by the capturing group, although not saved to the capturing group, is actually present in the result of the $ four expression that matches the content, generally, does not exist within the $ , so they match the result of a 0-width

A better way to understand them is to use them as an additional condition rather than as part of a regular expression.

To better illustrate, first say "gap" concept, "gap" is 0 width, it is just a position in the string, not the actual character, such as the string "AB", in front of "a", "a" and "B", and "B" behind it, there is a "gap", which means that the entire string has three "slits." ”

(? =exp) attaches a condition to the "gap" after which the "gap" must be able to match the content of exp
(?! EXP) attaches a condition to the "gap" after which the "gap" must not be able to match the content of exp
(? <=exp) attach a condition to the front of the "gap", that is, the "gap" must be able to match the content of exp
(? <!exp) attach a condition to the front of the "gap", that is, the "gap" must not be able to match the content of exp

Examples are as follows:
<[^>]*> expression Arbitrary HTML tags

Attach a condition
< (?! IMG) [^>]*>
This means all tags except the tag, look at the actual example


C # code
String test = "<p><a href=" http://anmo./"title=" bed Waiting for You "> ";
MatchCollection mc = regex.matches (Test, @ "<" (?!) IMG) [^>]*> ", RegexOptions. ignorecase);
foreach (Match m in MC)
{
richTextBox1.Text + + + M.value + "n";
}

The output results are:
<p>
<a href= "http://www.111cn.net/" >
</a>
</p>

Then look at the < (?!) IMG) [^>]*> This regular expression
(?! IMG) where the "gap" is "<" and the first character behind it "gap", it means that, in the "gap" behind, Can not be img, the whole expression meaning is not match tag

Similarly, < (? =img) [^>]*> only matches tags

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.