- •Лекция 2
- •Общие сведения
- •Классы для работы с regex
- •Простой пример
- •Простой пример
- •Метасимволы
- •Классы символов
- •Простой класс
- •Отрицание
- •Диапазон
- •Объединения
- •Пересечения
- •Вычитание
- •Предопределенные классы
- •Примеры
- •Квантификаторы
- •Квантификаторы
- •Совпадения нулевой длины
- •Совпадения нулевой длины
- •Квантификаторы
- •Использование групп и классов с квантификаторами
- •Жадные, ленивые и захватывающие квантификаторы
- •Жадные, ленивые и захватывающие квантификаторы
- •Группы
- •Обратные ссылки
- •Граничные мета-символы (boundary matchers)
- •Граничные мета-символы (boundary matchers)
- •Перечисление
- •Методы класса Pattern
- •Методы класса Matcher
- •Методы класса Matcher
- •Методы класса Matcher
Лекция 2
Регулярные выражения
Общие сведения
•Регулярные выражения (regex или regexp) – это правила задания шаблонов для поиска, изменения и манипулирования строками.
•1950 – regular sets (Stephen Cole Kleene)
•1962 – язык SNOBOL (поиск по шаблону)
•1987 – язык Perl
•1988 – язык TCL
Классы для работы с regex
•Пакет: java.util.regex (с Java 1.4, 2002г)
•Pattern – объект-шаблон, представляющий регулярное выражени
•Matcher – объект, интерпретирующий шаблон и выполняющий операции над строками
•PatternSyntaxException - исключение (неконтролируемое!), возникающее при ошибке в шаблоне
Простой пример
Console console = System.console();
Pattern pattern = Pattern.compile(console.readLine("%nEnter your regex: "));
Matcher matcher = pattern.matcher(console.readLine("Enter input string to search: "));
while (matcher.find()) {
console.format("I found the text \"%s\" starting at " + "index %d and ending at index %d.%n", matcher.group(),
matcher.start(),
matcher.end()); found = true;
}
Простой пример
Выполнение программы:
Enter your regex: foo
Enter input string to search: foo
I found the text "foo" starting at index 0 and ending at index 3.
Выполнение программы:
Enter your regex: foo
Enter input string to search: foofoofoo
I found the text "foo" starting at index 0 and ending at index 3.
I found the text "foo" starting at index 3 and ending at index 6.
I found the text "foo" starting at index 6 and ending at index 9.
Метасимволы
Изменим шаблон на “cat.”:
Enter your regex: cat.
Enter input string to search: cats
I found the text "cats" starting at index 0 and ending at index 4.
«точка» - метасимвол, обозначающий любой символ.
Другие метасимволы:
([{\^-$|]})?*+.
Два способа заставить интерпретатор трактовать метасимволы как обычные символы:
1)Использовать обратную косую черту перед символом
2)Заключить символы между \Q и \E
Классы символов
Класс символов – набор символов в [ ], определяющий сопоставление одного символа в интерпретируемой строке.
Классы символов:
[abc] |
a, b или c (простой класс) |
[^abc] |
Любой символ кроме a,b или с |
|
(отрицание) |
[a-z] |
все символы от а до z (диапазон) |
[a-d[m-p]] |
все символы от a до d и от m до p |
|
(объединение). Аналогично [a-dm-p] |
[a-z&&[def]] |
d,e или f (пересечение) |
[a-z&&[^bc]] |
от a до z кроме b и c (вычитание). |
|
Аналогично [ad-z] |
[a-z&&[^m-p]] |
от a до z и не от m до p (вычитание). |
|
Аналогично [a-lq-z] |
Простой класс
Enter your regex: [bcr]at
Enter input string to search: bat
I found the text "bat" starting at index 0 and ending at index 3.
Enter your regex: [bcr]at
Enter input string to search: cat
I found the text "cat" starting at index 0 and ending at index 3.
Enter your regex: [bcr]at
Enter input string to search: rat
I found the text "rat" starting at index 0 and ending at index 3.
Enter your regex: [bcr]at
Enter input string to search: hat
No match found.
Отрицание
Enter your regex: [^bcr]at
Enter input string to search: bat
No match found.
Enter your regex: [^bcr]at
Enter input string to search: cat
No match found.
Enter your regex: [^bcr]at
Enter input string to search: rat
No match found.
Enter your regex: [^bcr]at
Enter input string to search: hat
I found the text "hat" starting at index 0 and ending at index 3.
Диапазон
Enter your regex: [a-c]
Enter input string to search: a
I found the text "a" starting at index 0 and ending at index 1.
Enter your regex: [a-c]
Enter input string to search: b
I found the text "b" starting at index 0 and ending at index 1.
Enter your regex: [a-c]
Enter input string to search: c
I found the text "c" starting at index 0 and ending at index 1.
Enter your regex: [a-c]
Enter input string to search: d
No match found.