|
@@ -1,109 +1,166 @@
|
|
-# Конспект лекции "Регулярные выражения"
|
|
|
|
-## Регулярки в C#
|
|
|
|
-```
|
|
|
|
-string s = "Бык тупогуб, тупогубенький бычок, у быка губа бела была тупа";
|
|
|
|
-Regex regex = new Regex(@"туп(\w*)");
|
|
|
|
-MatchCollection matches = regex.Matches(s);
|
|
|
|
-if (matches.Count > 0)
|
|
|
|
-{
|
|
|
|
- foreach (Match match in matches)
|
|
|
|
- Console.WriteLine(match.Value);
|
|
|
|
-}
|
|
|
|
-else
|
|
|
|
-{
|
|
|
|
- Console.WriteLine("Совпадений не найдено");
|
|
|
|
-}
|
|
|
|
-```
|
|
|
|
-```
|
|
|
|
-тупогуб
|
|
|
|
-тупогубенький
|
|
|
|
-тупа
|
|
|
|
-```
|
|
|
|
-## Поиск с группами
|
|
|
|
-```
|
|
|
|
-string text = "One car red car blue car";
|
|
|
|
-string pat = @"(\w+)\s+(car)";
|
|
|
|
|
|
+# Поиск, сортировка ("Университет")
|
|
|
|
+## Поиск
|
|
|
|
+```
|
|
|
|
+<Window x:Class="University.MainWindow"
|
|
|
|
+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
|
|
|
+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
|
|
|
+ xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
|
|
|
+ xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
|
|
|
+ xmlns:local="clr-namespace:University"
|
|
|
|
+ mc:Ignorable="d"
|
|
|
|
+ Title="University" Height="450" Width="800">
|
|
|
|
+ <Grid>
|
|
|
|
+ <Grid.RowDefinitions>
|
|
|
|
+ <RowDefinition Height="Auto" />
|
|
|
|
+ <RowDefinition Height="*" />
|
|
|
|
+ </Grid.RowDefinitions>
|
|
|
|
|
|
-Regex r = new Regex(pat, RegexOptions.IgnoreCase);
|
|
|
|
|
|
+ <StackPanel Orientation="Horizontal" Margin="10">
|
|
|
|
|
|
-Match m = r.Match(text);
|
|
|
|
-int matchCount = 0;
|
|
|
|
-// можно искать не одно вхождение, а несколько
|
|
|
|
-while (m.Success)
|
|
|
|
-{
|
|
|
|
- Console.WriteLine("Match"+ (++matchCount));
|
|
|
|
- // тут можно было бы перебирать по длине массива Groups,
|
|
|
|
- // но мы по своему шаблону и так знаем, что у нас две подгруппы
|
|
|
|
- for (int i = 1; i <= 2; i++)
|
|
|
|
- {
|
|
|
|
- Console.WriteLine($"Group {i}='{m.Groups[i]}'");
|
|
|
|
- }
|
|
|
|
- // поиск следующей подстроки соответсвующей шаблону
|
|
|
|
- m = m.NextMatch();
|
|
|
|
-}
|
|
|
|
-```
|
|
|
|
-```
|
|
|
|
-Match1
|
|
|
|
-Group 1='One'
|
|
|
|
-Group 2='car'
|
|
|
|
-Match2
|
|
|
|
-Group 1='red'
|
|
|
|
-Group 2='car'
|
|
|
|
-Match3
|
|
|
|
-Group 1='blue'
|
|
|
|
-Group 2='car'
|
|
|
|
-```
|
|
|
|
-## Параметр RegexOptions
|
|
|
|
-### 示例1
|
|
|
|
-```
|
|
|
|
-string s = "Бык тупогуб, тупогубенький бычок, у быка губа бела была тупа";
|
|
|
|
-Regex regex = new Regex(@"\w*губ\w*");
|
|
|
|
-```
|
|
|
|
-```
|
|
|
|
-Process finished with exit code 0.
|
|
|
|
-```
|
|
|
|
-### 例子2
|
|
|
|
-```
|
|
|
|
-string s = "456-435-2318";
|
|
|
|
-Regex regex = new Regex(
|
|
|
|
- @"\d{3}-\d{3}-\d{4}");
|
|
|
|
-```
|
|
|
|
-```
|
|
|
|
-Process finished with exit code 0.
|
|
|
|
-```
|
|
|
|
-## Проверка на соответствие строки формату
|
|
|
|
-```
|
|
|
|
-string pattern = @"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
|
|
|
|
- @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$";
|
|
|
|
-while (true)
|
|
|
|
|
|
+ <Label
|
|
|
|
+Content="искать"
|
|
|
|
+VerticalAlignment="Center"/>
|
|
|
|
+ <TextBox
|
|
|
|
+Width="200"
|
|
|
|
+VerticalAlignment="Center"
|
|
|
|
+x:Name="SearchFilterTextBox"
|
|
|
|
+KeyUp="SearchFilter_KeyUp"/>
|
|
|
|
+ <Label
|
|
|
|
+ Content="Возраст:"
|
|
|
|
+ VerticalAlignment="Center"/>
|
|
|
|
+ <RadioButton
|
|
|
|
+ GroupName="Age"
|
|
|
|
+ Tag="1"
|
|
|
|
+ Content="по возрастанию"
|
|
|
|
+ IsChecked="True"
|
|
|
|
+ Checked="RadioButton_Checked"
|
|
|
|
+ VerticalAlignment="Center"/>
|
|
|
|
+ <RadioButton
|
|
|
|
+ GroupName="Age"
|
|
|
|
+ Tag="2"
|
|
|
|
+ Content="по убыванию"
|
|
|
|
+ Checked="RadioButton_Checked"
|
|
|
|
+ VerticalAlignment="Center"/>
|
|
|
|
+ </StackPanel>
|
|
|
|
+
|
|
|
|
+ <ListView x:Name="StudentListView" Grid.Row="1" Margin="10">
|
|
|
|
+ <ListView.View>
|
|
|
|
+ <GridView>
|
|
|
|
+ <GridViewColumn Header="Имя" DisplayMemberBinding="{Binding Name}" />
|
|
|
|
+ <GridViewColumn Header="Курс" DisplayMemberBinding="{Binding Course}" />
|
|
|
|
+ <GridViewColumn Header="Национальность" DisplayMemberBinding="{Binding Nationality}" />
|
|
|
|
+ <GridViewColumn Header="Возраст" DisplayMemberBinding="{Binding Age}" />
|
|
|
|
+ </GridView>
|
|
|
|
+ </ListView.View>
|
|
|
|
+ </ListView>
|
|
|
|
+ </Grid>
|
|
|
|
+</Window>
|
|
|
|
+```
|
|
|
|
+```
|
|
|
|
+using System;
|
|
|
|
+using System.Collections.Generic;
|
|
|
|
+using System.Linq;
|
|
|
|
+using System.Windows;
|
|
|
|
+using System.Windows.Controls;
|
|
|
|
+using System.Windows.Input;
|
|
|
|
+
|
|
|
|
+namespace University
|
|
{
|
|
{
|
|
- Console.WriteLine("Введите адрес электронной почты");
|
|
|
|
- string email = Console.ReadLine();
|
|
|
|
-
|
|
|
|
- if (Regex.IsMatch(email, pattern, RegexOptions.IgnoreCase))
|
|
|
|
|
|
+ public partial class MainWindow : Window
|
|
{
|
|
{
|
|
- Console.WriteLine("Email подтвержден");
|
|
|
|
- break;
|
|
|
|
|
|
+ private List<Student> students;
|
|
|
|
+ private string searchFilter = "";
|
|
|
|
+ private bool sortAsc = true;
|
|
|
|
+
|
|
|
|
+ public MainWindow()
|
|
|
|
+ {
|
|
|
|
+ InitializeComponent();
|
|
|
|
+
|
|
|
|
+ // Инициализируем список студентов
|
|
|
|
+ InitializeData();
|
|
|
|
+
|
|
|
|
+ // Отображаем всех студентов в listview
|
|
|
|
+ UpdateStudentList(students);
|
|
|
|
+ }
|
|
|
|
+ private void SearchFilter_KeyUp(object sender, KeyEventArgs e)
|
|
|
|
+ {
|
|
|
|
+ searchFilter = SearchFilterTextBox.Text;
|
|
|
|
+ Invalidate();
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ private void Invalidate()
|
|
|
|
+ {
|
|
|
|
+ throw new NotImplementedException();
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ private void InitializeData()
|
|
|
|
+ {
|
|
|
|
+ // Создаем список студентов
|
|
|
|
+ students = new List<Student>
|
|
|
|
+ {
|
|
|
|
+ new Student { Name = "Джейк Ли", Course = 1, Nationality = "Китаец", Age = 19 },
|
|
|
|
+ new Student { Name = "Ариадна Санчес", Course = 2, Nationality = "Испанец", Age = 20 },
|
|
|
|
+ new Student { Name = "Эдвард Каллен", Course = 1, Nationality = "Американец", Age = 20 },
|
|
|
|
+ new Student { Name = "Эндрю Уилсон", Course = 3, Nationality = "Американец", Age = 21 },
|
|
|
|
+ new Student { Name = "Хэй Вэнь", Course = 3, Nationality = "Китаец", Age = 22 },
|
|
|
|
+ new Student { Name = "Семен Хомяк", Course = 4, Nationality = "Русский", Age = 23 },
|
|
|
|
+ };
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ private void FilterComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
|
|
|
|
+ {
|
|
|
|
+ List<Student> filteredStudents = new List<Student>();
|
|
|
|
+
|
|
|
|
+ // Фильтруем список студентов по выбранному критерию
|
|
|
|
+
|
|
|
|
+ UpdateStudentList(filteredStudents);
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ private void UpdateStudentList(List<Student> studentsToDisplay)
|
|
|
|
+ {
|
|
|
|
+ StudentListView.ItemsSource = studentsToDisplay;
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ private void RadioButton_Checked(object sender, RoutedEventArgs e)
|
|
|
|
+ {
|
|
|
|
+ sortAsc = (sender as RadioButton).Tag.ToString() == "1";
|
|
|
|
+ InvalidateVisual(); // Исправлено имя метода
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ private void SortByAgeButton_Click(object sender, RoutedEventArgs e)
|
|
|
|
+ {
|
|
|
|
+ // Сортируем список студентов по возрасту
|
|
|
|
+ List<Student> sortedStudents = students.OrderBy(student => student.Age).ToList();
|
|
|
|
+
|
|
|
|
+ // Если нужно отсортировать по убыванию, разворачиваем список
|
|
|
|
+ if (!sortAsc)
|
|
|
|
+ {
|
|
|
|
+ sortedStudents.Reverse();
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ // Обновляем список студентов в ListView
|
|
|
|
+ UpdateStudentList(sortedStudents);
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ private IEnumerable<Student> FilteredStudentList
|
|
|
|
+ {
|
|
|
|
+ get
|
|
|
|
+ {
|
|
|
|
+ // сохраняем во временную переменную полный список
|
|
|
|
+ var res = students;
|
|
|
|
+
|
|
|
|
+ return res;
|
|
|
|
+ }
|
|
|
|
+ }
|
|
}
|
|
}
|
|
- else
|
|
|
|
|
|
+
|
|
|
|
+ class Student
|
|
{
|
|
{
|
|
- Console.WriteLine("Некорректный email");
|
|
|
|
|
|
+ public string Name { get; set; }
|
|
|
|
+ public int Course { get; set; }
|
|
|
|
+ public string Nationality { get; set; }
|
|
|
|
+ public int Age { get; set; }
|
|
}
|
|
}
|
|
}
|
|
}
|
|
```
|
|
```
|
|
-```
|
|
|
|
-Введите адрес электронной почты
|
|
|
|
-dkljfsljkf@gmail.com
|
|
|
|
-Email подтвержден
|
|
|
|
-```
|
|
|
|
-## Замена и метод Replace
|
|
|
|
-```
|
|
|
|
-string s = "Мама мыла раму. ";
|
|
|
|
-string pattern = @"\s+";
|
|
|
|
-string target = " ";
|
|
|
|
-Regex regex = new Regex(pattern);
|
|
|
|
-string result = regex.Replace(s, target);
|
|
|
|
-```
|
|
|
|
-```
|
|
|
|
-Process finished with exit code 0.
|
|
|
|
-```
|
|
|
|
|
|
+![](./img/Снимок%20экрана%202024-04-29%20083601.png)
|