Поиск строк с помощью строковых методов 


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



ЗНАЕТЕ ЛИ ВЫ?

Поиск строк с помощью строковых методов



Тип string, являющийся псевдонимом класса System..::.String, позволяет использовать несколько полезных методов для поиска содержимого строки. В следующем примере используются методы IndexOf, LastIndexOf, StartsWith и EndsWith.

Пример

ß---


How to: Search Strings Using Regular Expressions

The System.Text.RegularExpressions..::.Regex class can be used to search strings. These searches can range in complexity from very simple to making full use of regular expressions. The following are two examples of string searching by using the Regex class.

Example

The following code is a console application that performs a simple case-insensitive search of the strings in an array. The static method Regex..::.IsMatch performs the search given the string to search and a string that contains the search pattern. In this case, a third argument is used to indicate that case should be ignored. For more information, see System.Text.RegularExpressions..::.RegexOptions.

class TestRegularExpressions { static void Main() { string[] sentences = { "cow over the moon", "Betsy the Cow", "cowering in the corner", "no match here" }; string sPattern = "cow"; foreach (string s in sentences) { System.Console.Write("{0,24}", s); if (System.Text.RegularExpressions.Regex.IsMatch(s, sPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase)) { System.Console.WriteLine(" (match for '{0}' found)", sPattern); } else { System.Console.WriteLine(); } } } }
cow over the moon (match for 'cow' found) Betsy the Cow (match for 'cow' found) cowering in the corner (match for 'cow' found) no match here

Поиск строк с помощью регулярных выражений

Класс System.Text.RegularExpressions..::.Regex можно использовать для поиска строк. Поиск может отличаться по сложности и быть как простым, так и интенсивно использовать регулярные выражения. Ниже приведены два примера поиска строк с помощью класса Regex.

Пример

Следующий пример кода является консольным приложением, которое выполняет простой поиск строк в массиве без учета регистра. Статический метод Regex..::.IsMatch выполняет поиск заданной строки и строки, содержащей шаблон поиска. В этом случае третий аргумент указывает, что регистр знаков следует игнорировать.

ß---


The following code is a console application that uses regular expressions to validate the format of each string in an array. The validation requires that each string take the form of a telephone number in which three groups of digits are separated by dashes, the first two groups contain three digits, and the third group contains four digits. This is done by using the regular expression ^\\d{3}-\\d{3}-\\d{4}$.

class TestRegularExpressionValidation { static void Main() { string[] numbers = { "123-456-7890", "444-234-22450", "690-203-6578", "146-893-232", "146-839-2322", "4007-295-1111", "407-295-1111", "407-2-5555", }; string sPattern = "^\\d{3}-\\d{3}-\\d{4}$"; foreach (string s in numbers) { System.Console.Write("{0,14}", s); if (System.Text.RegularExpressions.Regex.IsMatch(s, sPattern)) { System.Console.WriteLine(" - valid"); } else { System.Console.WriteLine(" - invalid"); } } } }
123-456-7890 - valid 444-234-22450 - invalid 690-203-6578 - valid 146-893-232 - invalid 146-839-2322 - valid 4007-295-1111 - invalid 407-295-1111 - valid 407-2-5555 - invalid

Следующий пример кода является консольным приложением, которое использует регулярные выражения для проверки формата каждой строки массива. Для выполнения проверки требуется преобразование каждой строки в формат телефонного номера, в котором три группы цифр разделены дефисами, первые две группы содержат три цифры, а третья группа — четыре цифры. Для этого используется регулярное выражение ^\\d{3}-\\d{3}-\\d{4}$.

ß----




Поделиться:


Последнее изменение этой страницы: 2017-01-19; просмотров: 80; Нарушение авторского права страницы; Мы поможем в написании вашей работы!

infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 18.222.125.171 (0.004 с.)