The processing of strings is often designed in a program, such as ①: determining whether a user's input string conforms to the requirements, whether it is an illegal string, ②: Extracting a very complex string of parts needed in a program, etc.
This is usually very difficult to judge by writing algorithms, so it is very easy to think of regular expressions when dealing with strings.
One: Regular expression meta-character
• To learn a regular expression, understanding meta-characters is a challenge that must be overcome. No need to remember ·: matches any single character. For example, the regular expression "B.G" can match the following string: "Big", "Bug", "B g", but does not match "Buug", "B." G "Can match" Buug ". []: matches any one of the characters in the parentheses. For example, the regular expression "b[aui]g" matches the bug, big and bag, but does not match beg, Baug. You can use the hyphen "-" in parentheses to specify the interval of the character to simplify the representation, such as the regular expression [0-9] can match any numeric character, so that the regular expression "a[0-9]c" equivalent to "a[0123456789]c" can Match "a0c", "A1c", "A2C" such as String, you can also create multiple intervals, such as "[A-za-z]" can match any uppercase and lowercase letters, "[a-za-z0-9]" can match any uppercase or lowercase letters or numbers. • (): Defines the expression that is enclosed in () as a group, and saves the character that matches the expression to a staging area, which is useful when the string is extracted. To represent some characters as a whole. Change the priority, define the extraction group of two roles. | : A logical OR operation of two matching criteria. ' Z|food ' can match "z" or "food". ' (z|f) Ood ' matches "Zood" or "food". *: Matches 0 to more sub-expressions before it, and wildcards * okay. For example, the regular expression "zo*" can Match "Z", "Zo" and "Zoo", so ". *" means that you can match any string. "Z (b|c) *" →zb, ZBC, ZCB, ZCCC, ZBBBCCC. "Z (AB) *" can match Z, Zab, Zabab (with parentheses to change precedence). +: Matches the preceding subexpression one or more times, and * contrasts (0 to multiple). For example, the regular expression + + matches 9, 99, 999, and so on. "zo+" can Match "Zo" and "Zoo" and cannot match "Z". •? : matches the preceding subexpression 0 or one time. For example, "Do (es)?" can match "do" or "does". Typically used to match the "optional section". {n}: matches the determined n times. "Zo{2}" →zoo. For example, "e{2}" cannot match "E" in "bed", but can match two "E" in "seed". {n,}: matches at least n times. For example, "e{2,}" cannot match "E" in "bed", but can match all "E" in "Seeeeeeeed". {n,m}: matches at least n times and matches most M times. "e{1,3}" will match the first three "E" in "Seeeeeeeed". ^ (shift+6): Matches the start of a row. For example, the regular expression "^regex" can match the beginning of the string "Regex I will use", but does not match "I will use regex". ^ another meaning: No! $: Matches the line terminator (not yet understood). For example, the regular expression "cloud $" is able to match the string "Everything is a cloud" end, but can not match the string "cloud Ah" Regular expression is language-independent really is to express \d. Note that these shorthand expressions do not consider the escape character, where \ represents the character \, not the C # string level \, which requires the use of either @ or \ double escaping in C # code. Distinguishes between C # level transitions and regular expression level transfers, just as C # escapes the wildcards regular expression with an escape character of \. The transfer of regular expressions is after C # (layer exploits). Think of the escape character of C # as%. In C # It looks like @ "\-" is \-this ordinary string, just in
second,. The regular expressions in net
1. String matching:• Regular expressions are in the. NET is a string representation, this string format is very special, no matter how special, in the C # language seems to be a normal string, what the meaning of the Regex class inside the syntax analysis. • The main class of the regular expression (Regular expression): The Regex.IsMatch method is used to determine whether a string matches a regular expression. • Examples of string matching:
Regex.IsMatch ("BBBBG", "^b.*g $");
Regex.IsMatch ("BG", "^b.*g $");
Regex.IsMatch ("Gege", "^b.*g $");
Must not forget ^ and $, otherwise can also match yesbagit
For example:
• Determine if it is a valid ZIP code (6 digits) Regex.IsMatch ("100830", "^[0-9]{6}$")
Regex.IsMatch ("119", @ "^\d{6}$");
Explanation: The meta-character definition indicates that "[0-9]" represents any character from 0 to 9, "{6}" means that the preceding character matches 6, so {6} in "[0-9]{6}" indicates that the number is matched 6 times. The shorthand expression learns that "[0-9]" can be replaced by "\d", so the second way of writing "\d{6}" is correct. Don't forget @ or \\d.
• Determine if a string is an ID number, that is, 15 or 18 digits. • Error notation: Regex.IsMatch ("123456789123456789", @ "^\d{15}|\d{18}$"), which represents the beginning of a 15-digit number or the end of a 18-digit number. • Correct wording: Console.WriteLine (Regex.IsMatch ("0111111111111111", @ "^\d{15}$|^\d{18}$") or @ "^ (\d{15}|\d{18}) $" · Determine if the string is the correct domestic phone number, regardless of the extension. For example, "010-95555", "01095555", "95555" are the correct numbers. The area code is 3-bit or 4-bit. Regex.IsMatch ("123456-95555", @ "^\d{3,4}\-?\d+$") • "^\d{3,4}\-?\d+$" means that the matched character sequence should be composed of three to four digits, due to the hyphen "-" of the long-distance area code is optional, So the "?" is used here. Metacharacters for instructions. Because the hyphen "-" has a special meaning in the regular expression (representing a range, such as [0-9]), it is escaped. • Determine if a string is a valid email address. An email address is characterized by a sequence of characters, followed by the "@" sign, and a sequence of characters behind it, followed by the symbol ".", and finally the character sequence regex.ismatch ("[Email protected]", @ "^\[email protected]\w+\.\w+$ "); [] Any character in parentheses, \w letters, numbers, underscores, and more than one to many. Because. There is a special meaning in the regular expression, so for really want to express "." You need to transfer "\.". First think that the regular expression is language-independent. This is because in C #, the regular expression \ All represents the escape character, it's a bit messy. Consider the C # language first, in two steps to consider the regular expression syntax, and then consider how to find a regular expression in C # how to express.
• Trickery approach:Copying common regular expressions from the RegularExpressionValidator of ASP. In general, the job is to find out from the Internet.
2. String extraction:• Regular expressions can also be used for string extraction
Match match = Regex.match ("age=30", @ "^ (. +) = (. +) $");
if (match. Success)
{
Console.WriteLine (match. GROUPS[1]. Value);
Console.WriteLine (match. GROUPS[2]. Value);
}
The success property of the match indicates whether the match is successful, the contents of the regular expression () to be extracted, and then the groups property of the match to get all the extracted elements, note that the groups sequence number is 1, 0 has a special meaning
Greedy mode and non-greedy mode
• Extract the name from the text:
Match Match = Regex.match ("Hello everyone.") I'm S.H.E. I'm 22 years old. I'm sick, whining. Fffff "," I am (. +). ");//No Add ^$.
• See the results. +, * Matches by default is greedy (greedy): as many matches as possible until "greedy a little" after the matching pattern can not match until then.
• Add after +, * to become non-greedy mode (? Other uses): match the pattern as soon as possible after the match. Modified to "I am (. +?)." "
• The general development of the time without deliberately to decorate for the non-greedy mode, only when the bug encountered when found to be greedy mode problem to solve. Because the greedy efficiency is high.
Matching Groups• Regular expressions can output all matching content from a piece of text. Match gets the first one that matches. The Regex.Matches method can get all the matches. Note the difference: The difference between the match and group: see note 1 • Exercise: Extracting all numbers from a piece of text
MatchCollection matches = regex.matches ("Hello everybody, I am hebe, I am 22 years old, height 180, our team has 3 female female!") ", @" \d+ ");
foreach (match match in matches)
{Console.WriteLine (match. Value);}
3.c# string Extraction Sample code:
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Windows.Forms;usingSystem.Text.RegularExpressions;namespaceThe regular expression takes the value inside the parentheses { Public Partial classForm1:form { PublicForm1 () {InitializeComponent (); } //use regular expressions to take out the required data in the string//This example removes the value of Host,port, already SID Private voidButton1_Click (Objectsender, EventArgs e) { stringhost; stringPORT; stringSID; stringstr ="( DESCRIPTION = (Address_list = (ADDRESS = (PROTOCOL = TCP) (HOST = Ahnu) (PORT = 1521))) (Connect_data = (SID =orcl))) "; STR=Str. Trim (); //method One: one to take, to be targeted,Match match = Regex.match (str,@"\ (host=? (. +?) \)"); if(match. Success) {host= match. groups[1]. Value; } Match= Regex.match (str,@"\ (port=? (. +?) \)"); if(match. Success) {PORT= match. groups[1]. Value; } Match= Regex.match (str,@"\ (sid=? (. +?) \)"); if(match. Success) {SID= match. groups[1]. Value; } //method Two: Take out all the matching strings, here is just an introduction if more than one string match how to handle. MatchCollection MTS = Regex.Matches (str,@"\ (HOST (. +?) =? (.+?) \)"); for(inti =0; I < MTS. Count; i++) {Match Mt=Mts[i]; MessageBox.Show (Mt. Value); MessageBox.Show (Mt. groups[1]. Value); } //method Three: First take out a portion and then extract it as a new string, which avoids the partial write error of the regular expression and does not match the situation. Match m = Regex.match (str,@".+?=.+?=.+?=(.+?) \)\).+?=(.+?) \)\)"); if(m.success) {stringS1 = m.groups[1]. Value;//"(PROTOCOL = TCP) (HOST = Ahnu) (PORT = 1521") stringS2 = m.groups[2]. Value;//(SID =orcl " if(m.success) {stringSTR3 = m.groups[1]. Value; stringSTR4 = m.groups[2]. Value;//"(PROTOCOL = TCP) (HOST = Ahnu) (PORT = 1521") if(m.success) {host= m.groups[1]. Value; PORT= m.groups[2]. Value; } m= Regex.match (S2,@"\(.+?=(.+)"); if(m.success) {SID= m.groups[1]. Value; } } } } }}
Use of regular expressions, string extraction, string matching (C # language)