logo search
CSharp_Prog_Guide

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

Класс 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}$.

----

How to: Join Multiple Strings

There are two ways to join multiple strings: using the + operator that the String class overloads, and using the StringBuilder class. The + operator is easy to use and makes for intuitive code, but it works in series; a new string is created for each use of the operator, so chaining multiple operators together is inefficient. For example:

string two = "two";

string str = "one " + two + " three";

System.Console.WriteLine(str);

Although four strings appear in the code, the three strings being joined and the final string containing all three, five strings are created in total because the first two strings are joined first, creating a string containing "one two." The third is appended separately, forming the final string stored in str.

Alternatively, the StringBuilder class can be used to add each string to an object that then creates the final string in one step. This strategy is demonstrated in the following example.

Example

The following code uses the Append method of the StringBuilder class to join three strings without the chaining effect of the + operator.

class StringBuilderTest

{

static void Main()

{

string two = "two";

System.Text.StringBuilder sb = new System.Text.StringBuilder();

sb.Append("one ");

sb.Append(two);

sb.Append(" three");

System.Console.WriteLine(sb.ToString());

string str = sb.ToString();

System.Console.WriteLine(str);

}

}