標籤:
Regular expressions
一.關鍵概念
1.The result of applying a regular expression to a string is one of the following: To find out whether the string matches the regular expression. To return a substring. To return a new string representing a modification of some part of the original string.
2.System.Text.RegularExpressions namespace is the home of objects associated with regular expressions.
二.運行執行個體
1.代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace study5
{
class Program
{
static void Main(string[] args)
{
string string1 = "This is a test string"; // find any nonwhitespace followed by whitespa Regex theReg = new Regex(@"(\S+)\s"); // get the collection of matches MatchCollection theMatches = theReg.Matches(string1); // iterate through the collection foreach (Match theMatch in theMatches) { Console.WriteLine("theMatch.Length: {0}", theMatch.Length); if (theMatch.Length != 0) { Console.WriteLine("theMatch: {0}", theMatch.ToString( )); } }
}
}
}
2.輸出結果
theMatch.Length: 5
theMatch: This
theMatch.Length: 3
theMatch: is
theMatch.Length: 2
theMatch: a
theMatch.Length: 5
theMatch: test
請按任意鍵繼續. . .
Exceptions
1.關鍵字 try catch finally throw
2.範例程式碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace study5
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("Entering try block...");
throw new System.ApplicationException();
Console.WriteLine("Exiting try block...");
}
catch
{
// Note: simplified example, it is not really solve the exception.
Console.WriteLine("Exception caught and handled.");
}
}
}
}
3.輸出結果
System.DivideByZeroException: Msg: Divided 0
在 study5.Program.DoDivide(Double a, Double b) 位置 c:\Users\史航宇\Documents
\Visual Studio 2013\Projects\study5\study5\Program.cs:行號 32
在 study5.Program.Main(String[] args) 位置 c:\Users\史航宇\Documents\Visual S
tudio 2013\Projects\study5\study5\Program.cs:行號 14
Close file here.
請按任意鍵繼續. . .
Delegates and Events
1.範例程式碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace ConsoleApplication5
{
class Program
{
static int counter = 0;
static string displayString = "World,I love you!\n世界,我喜歡你!\n";
static void Main(string[] args)
{
Timer myTimer = new Timer(100);
myTimer.Elapsed += new ElapsedEventHandler(WriteChar);
myTimer.Start();
Console.ReadKey();
}
static void WriteChar(object source, ElapsedEventArgs e)
{
Console.Write(displayString[counter++ % displayString.Length]);
}
}
}
2.輸出結果
World,I love you!
世界,我喜歡你!
(一個字一個字的出現)
C#部落格第六周