Два примера настраиваемых форматов



В следующих фрагментах кода демонстрируется настраиваемое форматирование чисел. В обоих случаях заменитель цифры (#) в строке пользовательского формата отображает числовые данные, а все остальные знаки копируются в выходную строку.

Double myDouble = 1234567890; String myString = myDouble.ToString( "(###) ### - ####" ); // The value of myString is "(123) 456 – 7890".   int MyInt = 42; MyString = MyInt.ToString( "My Number = #" ); // In the U.S. English culture, MyString has the value: // "My Number = 42".

NET Framework Regular Expressions

Regular expressions provide a powerful, flexible, and efficient method for processing text. The extensive pattern-matching notation of regular expressions allows you to quickly parse large amounts of text to find specific character patterns; to extract, edit, replace, or delete text substrings; or to add the extracted strings to a collection in order to generate a report. For many applications that deal with strings (such as HTML processing, log file parsing, and HTTP header parsing), regular expressions are an indispensable tool.

Microsoft .NET Framework regular expressions incorporate the most popular features of other regular expression implementations such as those in Perl and awk. Designed to be compatible with Perl 5 regular expressions, .NET Framework regular expressions include features not yet seen in other implementations, such as right-to-left matching and on-the-fly compilation.

The .NET Framework regular expression classes are part of the base class library and can be used with any language or tool that targets the common language runtime, including ASP.NET and Visual Studio 2005.


Регулярные выражения в .NET Framework

Регулярные выражения предоставляют мощный, гибкий и эффективный метод обработки текста. Обширная система обозначений для поиска соответствий позволяет выполнять быстрый разбор большого текста и поиск определенных групп символов для извлечения, изменения, замены или удаления текстовых подстрок, а также для добавления извлеченных строк в коллекцию для создания отчета. Регулярные выражения являются необходимым инструментом для многих приложений, которые выполняют строковые операции (например, обработка HTML, разбор файла журнала и разбор заголовка HTTP).

В регулярные выражения Microsoft .NET Framework включены наиболее распространенные методы, встречающиеся в других реализациях регулярных выражений, например в языках Perl и awk. Регулярные выражения .NET Framework совместимы с регулярными выражениями Perl 5 и содержат такие функции, как обратное (справа налево) сопоставление и компиляция в процессе обработки, которые еще не реализованы в других продуктах.

Классы регулярных выражений .NET Framework являются частью библиотеки базовых классов, их можно использовать с другим языком или инструментом, работающим с общеязыковой средой выполнения, например ASP.NET и Visual Studio 2005.

 


Regular Expressions as a Language

The regular expression language is designed and optimized to manipulate text. The language comprises two basic character types: literal (normal) text characters and metacharacters. The set of metacharacters gives regular expressions their processing power.

You are probably familiar with the ? and * metacharacters used with the DOS file system to represent any single character or group of characters. The DOS file command COPY *.DOC A: commands the file system to copy any file with a .DOC file name extension to the disk in drive A. The metacharacter * stands in for any file name in front of the file name extension .DOC. Regular expressions extend this basic idea many times over, providing a large set of metacharacters that make it possible to describe very complex text-matching expressions with relatively few characters.

For example, the regular expression \s2000, when applied to a body of text, matches all occurrences of the string "2000" that are preceded by any white-space character, such as a space or a tab.

Note:
If you are using C++, C#, or JScript, special escape characters, such as \s, must be preceded by an additional backslash (for example, "\\s2000") to signal that the backslash in the escape character is a literal character. Otherwise, the regular expression engine treats the backslash and the s in \s as two separate operators. You do not have to add the backslash if you are using Visual Basic 2005. If you are using C#, you can use C# literal strings, which are prefixed with @ and disable escaping (for example, @"\s2000").

Regular expressions can also perform searches that are more complex. For example, the regular expression (?<char>\w)\k<char>, using named groups and backreferencing, searches for adjacent paired characters. When applied to the string "I'll have a small coffee" it finds matches in the words "I'll", "small", and "coffee".

The following sections detail the set of metacharacters that define the .NET Framework regular expression language and show how to use the regular expression classes to implement regular expressions in your applications.


Дата добавления: 2019-03-09; просмотров: 191; Мы поможем в написании вашей работы!

Поделиться с друзьями:






Мы поможем в написании ваших работ!