PV178: Programming for the CLI Environment Seminar: Week 4 Michal Ordelt, Tomáš Pochop Institute of Computer Science and Faculty of Informatics Masaryk University March 25, 2007 * S Regular expressions i 1 using System . Text. Regu la rExpressions 2 2 private Regex rx; 3 3 rx = new Regex ( p a t t e r n ) ; 4 4 i f ( rx . l s M a t c h ( i n p u t T e x t ) ) { 5 5 \\some match found , do something 6 6 } * S Some regular expressions elements Quantifiers: + One or more matches * Zero, one or more matches Character classes: \d Decimal digit \s Any whitespace . Any character except \n For more regular expressions language elements see MSDN. * s Q (?'groupname'pattern) Captures the matched substring into a group groupname. The string used for groupname must not contain any punctuation and it cannot begin with a number. B Class M a t c h C o l l e c t i o n represents the set of successful matches found by iteratively applying a regular expression pattern to the input string. B M a t c h C o l l e c t i o n Regex.Matches(string i n p u t ) method searches an input string for all occurrences of a regular expression and returns all the successful matches as if Match were called numerous times. B Match. Groups ["groupname "] .Value returns the matched substring for group groupname. Regular expressions grouping example i //capture subexpressions groups number and text 2 rx = new Regex(@" ( ? ' n u m b e r ' \ d + ) \ s + ( ? ' t e x t ' ˇ * ) " ); 3 M atchCol lection matches = rx . Matches( someString ); 4 //go through all matched elements 5 foreach (Match match J j i matches)! e //access groups 7 string num = match . Groups [" number" ] . Value ; s string t e x t = match . Groups [" t e x t " ] . Value ; } * S A simple .sub subtitle file contains a lot of lines in format: {startframe}{endframe}Text to be shown. Write an application that moves the subtitle forward or back by a specified amount of time. First implement class Line representing a single line of the subtitle file. This class stores the startframe, endframe and text, and provide the method Move ( i n t 64 seconds, double framerate) which moves the startframe and endframe by the specified number of second, at the specified framerate. The overriden method ToStringO returns the line in the .sub format. Hints: Framerate means number of frames per second The example .sub file has framerate 23.976 To convert double to Int64 use Convert .ToInt64(double) Next implement class Subtitle : IEnumerable representing the subtitle file. This class reads one by one all lines from the input file, using regular expresions fills Line class and returns it as an enumerator. Move each line by the specified amount of seconds and write it to the output file. The input file, framerate, time and output file are set from command line as arguments. Hints: To read text from file use TextReader class Use encoding Encoding.GetEncoding(1250) for file I/O Remember to close all streams, readers and writers. To write to a file use the TextWriter class. Example: i //write to the file file, out 2 F i l e S t r e a m fs = F i le . C r e a t e (" f i I e . o u t " ); 3 T e x t W r i t e r w r ; 4 //assign the textwriter to the filestream 5 wr = new S t r e a m W r i t e r ( f s , e E n c o d i n g . G e t E n c o d i n g ( 1 2 5 0 ) ) ; 7 //write a line to the file s w r . W r i t e L i n e ( " W r i t t e n ^ i n ^ f i l e " ); 9 w r . C l o s e ( ) ; //close the writer io f s . Close ( ) ; //close the stream C # , like many object-oriented languages, handles errors and abnormal conditions with exceptions. An exception is an object that encapsulates information about an unusual program occurrence. It is important to distinguish between bugs, errors, and exceptions. A bug is a programmer mistake that should be fixed before the code is shipped. Exceptions are not a protection against bugs. Although a bug might cause an exception to be thrown, you should not rely on exceptions to handle your bugs. Rather, you should fix the bug. When your program encounters an exceptional circumstance, such as running out of memory, it throws (or "raises") an exception. When an exception is thrown, execution of the current function halts and the stack is unwound until an appropriate exception handler is found. Exceptions To signal an abnormal condition in a C # class, you throw an exception. To do this, use the keyword throw. This code creates a new instance of System.Exception and then throws it: i E x c e p t i o n e x c e p t i o n ; 2 e x c e p t i o n = new E x c e p t i o n (" S o m e t h i n g ^ b a d ^ h a p p e n e d " ) 3 throw e x c e p t i o n ; * s Exceptions handling In C#, an exception handler is called a catch block and is created with the catch keyword. i try_{ 2 //an exception can occur here 3 } 4 catch ( ExceptionType e ) { 5 //here we catch an ExceptionType exception e //and all derived from ExceptionType too * } s f i n a l l y { 9 //this code is always executed * s Exception class: useful members string Message The error message that explains the reason for the exception. string StackTrace A string that describes the contents of the call stack string ToStringO The default implementation obtains the name of the class that threw the current exception, the message, the result of calling ToString on the inner exception, and the StackTrace. You can create your own exception classes by deriving from the Exception class. Example: i //derive from the Exception class 2 public class MyException : Exception { 3 //constructor with message 4 public MyException ( s t r i n g message) 5 : base( message) { e } //ctor with message and inner exception 7 public Exception ( s t r i n g message, Exception in s : base( message , i n n e r ) { } 10 } Raise MyException: i throw new MyException (" My^ except ion ^occured !" ); Exceptions task Add exceptions handling to the Subtitle timing application and cover all possible problems, that may occur (can't read from input file, can't write to output file, wrong format of line, etc.). Try to use your own exception too. * s ˇ s