Interpreting Regular Expressions in C #

Source: Internet
Author: User

Over the years, many programming languages and tools have supported regular expressions ,. NET base class library contains a namespace and a series of classes that can fully utilize the power of Rule expressions, and they are also compatible with future rule expressions in Perl 5.
  
In addition, the regexp class can complete some other functions, such as the combination mode from right to left and expression editing.
  
In this article, I will briefly introduce System. text. classes and methods in RegularExpression, examples of string matching and replacement, and detailed information about the group structure. Finally, we will introduce some common expressions that you may use.
  
Basic knowledge to be mastered

The knowledge of Rule expressions may be one of the things that many programmers often forget. In this article, we will assume that you have mastered the usage of regular expressions, especially the expressions in Perl 5 .. NET regexp class is a superset of expressions in Perl 5, So theoretically it will be a good start point. We also assume that you have basic knowledge of C # syntax and. NET architecture.
  
If you do not have knowledge about Rule expressions, I suggest you start with the Perl 5 syntax. The authoritative book on Rule expressions is written by Jeffrey fredel. We strongly recommend that you read this book for readers who wish to have a deep understanding of expressions.
  
RegularExpression combination

The regexp rule class is included in the System. Text. RegularExpressions. dll file. You must reference this file when compiling the application software. For example:

Csc r: System. Text. RegularExpressions. dll foo. cs

The command will create the foo.exe file, which references the System. Text. RegularExpressions file.
  
Namespace Introduction

The namespace contains only six classes and one definition. They are:
  
Capture: contains a matching result;
CaptureCollection: the sequence of Capture;
Group: the result of a Group record, inherited by Capture;
Match: the matching result of an expression, inherited by the Group;
MatchCollection: a sequence of Match;
MatchEvaluator: the proxy used to perform the replacement operation;
Regex: An Example of the compiled expression.

The Regex class also contains some static methods:

Escape: Escape the Escape characters in the regex string;
IsMatch: If the expression matches a string, this method returns a Boolean value;
Match: returns the instance of the Match;
Matches: returns a series of Match methods;
Replace: Replace the matching expression with the replacement string;
Split: returns a series of strings determined by expressions;
Unescape: do not escape characters in strings.

Simple Matching

First, we start to learn from simple expressions of the Regex and Match classes.
  
Match m = Regex. Match ("abracadabra", "(a | B | r) + ");
  
We now have an instance of the Match class that can be used for testing, for example: if (m. Success )...
If you want to use a matched string, you can convert it into a string:
  
Console. WriteLine ("Match =" + m. ToString ());
  
In this example, the following output is obtained: Match = abra. This is the matched string.
  
String replacement

Simple string replacement is very intuitive. For example, the following statement:
  
String s = Regex. Replace ("abracadabra", "abra", "zzzz ");
  
It returns the string zzzzzzcadzzzz, and all matched strings are replaced with zzzzzzz.

Now let's look at a complicated string replacement example:
  
String s = Regex. Replace ("abra", @ "^ s *(.*?) S * $ "," $1 ");
  
This statement returns the string abra, with leading and trailing spaces removed.
  
The preceding mode is useful for deleting leading and trailing spaces in any string. In C #, we often use letter strings. In a letter string, the compiler does not treat the character "" as an escape character. When the character "" is used to specify the Escape Character, @ "..." is very useful. It is also worth mentioning that $1 is used in string replacement, which indicates that the replacement string can only contain the replaced string.
  
Matching engine details

Now, we use a group structure to understand a slightly complex example. See the following example:
  
String text = "abracadabra1abracadabra2abracadabra3 ";
  
String pat = @"
  
(# Start of the first group
  
Abra # match the string abra
  
(# Start of the second group
  
Cad # matching string cad
  
)? # End of the second group (optional)
  
) # End of the first group
  
+ # Match once or multiple times
  
";

Contents

Class and structure instance comparison

Differences between classes and structures

How to Select structure or Class

I. Comparison of classes and structures:

Structure example:

Public struct Person
{
String Name;
Int height;
Int weight
Public bool overWeight ()
{
// Implement something
}
}
 
Class Example:
Public class TestTime
{
Int hours;
Int minutes;
Int seconds;
Public void passtime ()
{
// Implementation of behavior
}
}
 
Call process:

Public class Test
{
Public static ovid Main
{
Person Myperson = new Person // declaration Structure
TestTime Mytime = New TestTime // Declaration class
}
}
From the above example, we can see that the declaration of the class and the declaration of the structure are very similar, but the difference between struct and class is after the qualifier, and when used, similar methods are used to define new structures and new classes. What are the specific differences between classes and structures?

Ii. Differences between classes and structures

1. Value Type and reference type

Structure is value type: value type is allocated on the stack. All base types are structure types. For example, int corresponds to System. int32 structure. string corresponds to system. string Structure. You can create more value types by using the structure.

Class is a reference type: the reference type is allocated on the stack.

The execution efficiency of stacks is higher than the execution efficiency of stacks. However, the stack resources are limited and it is not suitable for processing large logical and complex objects. Therefore, structure processing is a small object to be treated as a base type, while classes process a certain business logic.

Because the structure is a value type, a value can be assigned between structures to create a new structure, while a class is a reference type. A value assignment between classes is just a copy reference.

Note:

1. Although the structure is different from the class type, their base types are all objects. in c #, all types of base types are objects.

2. although the New operator is used for structure initialization, the structure object is still allocated on the stack instead of the stack. If the new operator is not used, before all fields are initialized, the field remains unassigned and the object is unavailable.

2. Inheritance

Structure: it cannot be inherited from another structure or class. Although the structure is not explicitly declared using sealed, the structure is implicit sealed.

Class: fully scalable. Unless the declared sealed is displayed, the class can inherit other classes and interfaces, and its own can also be inherited.

Note: although the structure cannot be inherited, the structure can inherit interfaces, and methods are the same as class inheritance interfaces.

Example: structure implementation Interface

Interface IImage
{
Void Paint ();
}
Struct Picture: IImage
{
Public void Paint ()
{
// Painting code goes here
}
Private int x, y, z; // other struct members
}
 
3. Internal Structure:

Structure:

No default constructor exists, but you can add constructor.

No destructor

No abstract and sealed (because it cannot be inherited)

The protected modifier cannot exist.

You do not need to use new for initialization.

It is incorrect to initialize the instance field in the structure.

Class:

Default constructor available

Destructor

Abstract and sealed can be used.

There is a protected Modifier

New must be used for initialization.

3. How to Select a structure or a class

After discussing the similarities and differences between structures and classes, we will discuss how to choose a structure or a class:

1. The stack space is limited. For a large number of logical objects, creating classes is better than creating structures.

2. structure indicates lightweight objects such as dots, rectangles, and colors. For example, if an array containing 1000 vertex objects is declared, additional memory will be allocated to each referenced object. In this case, the structure cost is low.

3. Classes are the best choice for presentation of abstract and multi-level object Layers

4. In most cases, this type is the best choice for structure when it is only some data.


Related Article

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.