|
1 |
| -# Patterns and flags |
| 1 | +# Вступ: шаблони та прапори |
2 | 2 |
|
3 |
| -Regular expressions are patterns that provide a powerful way to search and replace in text. |
| 3 | +Регулярні вирази – потужний засіб пошуку та заміни тексту в рядках. |
4 | 4 |
|
5 |
| -In JavaScript, they are available via the [RegExp](mdn:js/RegExp) object, as well as being integrated in methods of strings. |
| 5 | +В JavaScript регулярні вирази реалізовані окремим об’єктом [RegExp](mdn:js/RegExp) та інтегровані у методи рядків. |
6 | 6 |
|
7 |
| -## Regular Expressions |
| 7 | +## Регулярні вирази |
8 | 8 |
|
9 |
| -A regular expression (also "regexp", or just "reg") consists of a *pattern* and optional *flags*. |
| 9 | +Регулярний вираз (він же "регексп", "регулярка" або просто "рег"), складається з *шаблону* (також кажуть "патерн") і необов’язкових *прапорів*. |
10 | 10 |
|
11 |
| -There are two syntaxes that can be used to create a regular expression object. |
| 11 | +Існує два синтаксиси для створення регулярного виразу. |
12 | 12 |
|
13 |
| -The "long" syntax: |
| 13 | +"Довгий" синтаксис: |
14 | 14 |
|
15 | 15 | ```js
|
16 |
| -regexp = new RegExp("pattern", "flags"); |
| 16 | +regexp = new RegExp ("шаблон", "прапори"); |
17 | 17 | ```
|
18 | 18 |
|
19 |
| -And the "short" one, using slashes `"/"`: |
| 19 | +Та "короткий" синтаксис, в якому використовуються слеши `"/"`: |
20 | 20 |
|
21 | 21 | ```js
|
22 |
| -regexp = /pattern/; // no flags |
23 |
| -regexp = /pattern/gmi; // with flags g,m and i (to be covered soon) |
| 22 | +regexp = /шаблон/; // без прапорів |
| 23 | +regexp = /шаблон/gmi; // з прапорами g,m та i (будуть описані далі) |
24 | 24 | ```
|
25 | 25 |
|
26 |
| -Slashes `pattern:/.../` tell JavaScript that we are creating a regular expression. They play the same role as quotes for strings. |
| 26 | +Слеши `pattern:/.../` говорять JavaScript про те, що це регулярний вираз. Вони відіграють таку саму роль, як і лапки для позначення рядків. |
27 | 27 |
|
28 |
| -In both cases `regexp` becomes an instance of the built-in `RegExp` class. |
| 28 | +Регулярний вираз `regexp` в обох випадках є об’єктом вбудованого класу `RegExp`. |
29 | 29 |
|
30 |
| -The main difference between these two syntaxes is that pattern using slashes `/.../` does not allow for expressions to be inserted (like string template literals with `${...}`). They are fully static. |
| 30 | +Основна різниця між цими двома синтаксами полягає в тому, що слеши `/.../` не допускають жодних вставок змінних (на зразок тих, що прописуються через `${...}`). Вони повністю статичні. |
31 | 31 |
|
32 |
| -Slashes are used when we know the regular expression at the code writing time -- and that's the most common situation. While `new RegExp` is more often used when we need to create a regexp "on the fly" from a dynamically generated string. For instance: |
| 32 | +Слеши використовуються, коли ми на момент написання коду точно знаємо, яким буде регулярний вираз - і це більшість ситуацій. А `new RegExp` - коли ми хочемо створити регулярний вираз "на льоту" з динамічно згенерованого рядка, наприклад: |
33 | 33 |
|
34 | 34 | ```js
|
35 |
| -let tag = prompt("What tag do you want to find?", "h2"); |
| 35 | +let tag = prompt("Який тег ви хочете знайти?", "h2"); |
36 | 36 |
|
37 |
| -let regexp = new RegExp(`<${tag}>`); // same as /<h2>/ if answered "h2" in the prompt above |
| 37 | +let regexp = new RegExp(`<${tag}>`); // те саме, що /<h2>/ при відповіді "h2" на запит вище |
38 | 38 | ```
|
39 | 39 |
|
40 |
| -## Flags |
| 40 | +## Прапори |
41 | 41 |
|
42 |
| -Regular expressions may have flags that affect the search. |
| 42 | +Регулярні вирази можуть мати прапори, які впливають на пошук. |
43 | 43 |
|
44 |
| -There are only 6 of them in JavaScript: |
| 44 | +У JavaScript їх всього шість: |
45 | 45 |
|
46 | 46 | `pattern:i`
|
47 |
| -: With this flag the search is case-insensitive: no difference between `A` and `a` (see the example below). |
| 47 | +: З цим прапором пошук не залежить від регістру: немає різниці між `A` та `a` (див. приклад нижче). |
48 | 48 |
|
49 | 49 | `pattern:g`
|
50 |
| -: With this flag the search looks for all matches, without it -- only the first match is returned. |
| 50 | +: З цим прапором пошук шукає всі збіги, без нього - лише перше. |
51 | 51 |
|
52 | 52 | `pattern:m`
|
53 |
| -: Multiline mode (covered in the chapter <info:regexp-multiline-mode>). |
| 53 | +: Багаторядковий режим (розглядається в розділі <info:regexp-multiline-mode>). |
54 | 54 |
|
55 | 55 | `pattern:s`
|
56 |
| -: Enables "dotall" mode, that allows a dot `pattern:.` to match newline character `\n` (covered in the chapter <info:regexp-character-classes>). |
| 56 | +: Вмикає режим "dotall", при якому крапка `pattern:.` може відповідати символу нового рядка `\n` (розглядається у розділі <info:regexp-character-classes>). |
57 | 57 |
|
58 | 58 | `pattern:u`
|
59 |
| -: Enables full Unicode support. The flag enables correct processing of surrogate pairs. More about that in the chapter <info:regexp-unicode>. |
| 59 | +: Вмикає повну підтримку Юнікоду. Прапор дозволяє коректну обробку сурогатних пар (докладніше про це у розділі <info:regexp-unicode>). |
60 | 60 |
|
61 | 61 | `pattern:y`
|
62 |
| -: "Sticky" mode: searching at the exact position in the text (covered in the chapter <info:regexp-sticky>) |
| 62 | +: Режим пошуку на конкретній позиції в тексті (описаний у розділі <info:regexp-sticky>) |
63 | 63 |
|
64 |
| -```smart header="Colors" |
65 |
| -From here on the color scheme is: |
| 64 | +```smart header="Кольорові позначення" |
| 65 | +Тут і далі в тексті використовується наступна колірна схема: |
66 | 66 |
|
67 |
| -- regexp -- `pattern:red` |
68 |
| -- string (where we search) -- `subject:blue` |
69 |
| -- result -- `match:green` |
| 67 | +- регулярний вираз - `pattern:червоний` |
| 68 | +- рядок (там, де відбувається пошук) -- `subject:синій` |
| 69 | +- результат -- `match:зелений` |
70 | 70 | ```
|
71 | 71 |
|
72 |
| -## Searching: str.match |
| 72 | +## Пошук: str.match |
73 | 73 |
|
74 |
| -As mentioned previously, regular expressions are integrated with string methods. |
| 74 | +Як вже згадувалося, використання регулярних виразів інтегровано у методи рядків. |
75 | 75 |
|
76 |
| -The method `str.match(regexp)` finds all matches of `regexp` in the string `str`. |
| 76 | +Метод `str.match(regexp)` для рядка `str` повертає збіги з регулярним виразом `regexp`. |
77 | 77 |
|
78 |
| -It has 3 working modes: |
| 78 | +У нього є три режими роботи: |
79 | 79 |
|
80 |
| -1. If the regular expression has flag `pattern:g`, it returns an array of all matches: |
81 |
| - ```js run |
82 |
| - let str = "We will, we will rock you"; |
| 80 | +1. Якщо в регулярного виразу є прапор `pattern:g`, то він повертає масив всіх збігів: |
| 81 | + ```js run |
| 82 | + let str = "За Вас правда, за вас слава і воля святая!"; |
| 83 | + alert(str.match(/вас/gi)); // Вас, вас (масив із 2х підрядків-збігів) |
| 84 | + ``` |
| 85 | + Зверніть увагу: знайдено як `match:Вас` так і `match:вас`, завдяки прапору `pattern:i`, який робить регулярний вираз реєстронезалежним. |
83 | 86 |
|
84 |
| - alert( str.match(/we/gi) ); // We,we (an array of 2 substrings that match) |
85 |
| - ``` |
86 |
| - Please note that both `match:We` and `match:we` are found, because flag `pattern:i` makes the regular expression case-insensitive. |
| 87 | +2. Якщо такого прапора немає, то повертається лише перший збіг у вигляді масиву, в якому за індексом `0` знаходиться збіг, і є властивості з додатковою інформацією про нього: |
| 88 | + ```js run |
| 89 | + let str = "За Вас правда, за вас слава і воля святая!"; |
87 | 90 |
|
88 |
| -2. If there's no such flag it returns only the first match in the form of an array, with the full match at index `0` and some additional details in properties: |
89 |
| - ```js run |
90 |
| - let str = "We will, we will rock you"; |
| 91 | + let result = str.match(/вас/i); // без прапора g |
91 | 92 |
|
92 |
| - let result = str.match(/we/i); // without flag g |
| 93 | + alert(result[0]); // Вас (перший збіг) |
| 94 | + alert(result.length); // 1 |
93 | 95 |
|
94 |
| - alert( result[0] ); // We (1st match) |
95 |
| - alert( result.length ); // 1 |
| 96 | + // Додаткова інформація: |
| 97 | + alert(result.index); // 0 (позиція збігу) |
| 98 | + alert(result.input); // За Вас правда, за вас слава і воля святая! (вихідний рядок) |
| 99 | + ``` |
| 100 | + У цьому масиві можуть бути інші індекси, крім `0`, якщо частина регулярного виразу виділена в дужки. Ми розберемо це у розділі <info:regexp-groups>. |
96 | 101 |
|
97 |
| - // Details: |
98 |
| - alert( result.index ); // 0 (position of the match) |
99 |
| - alert( result.input ); // We will, we will rock you (source string) |
100 |
| - ``` |
101 |
| - The array may have other indexes, besides `0` if a part of the regular expression is enclosed in parentheses. We'll cover that in the chapter <info:regexp-groups>. |
| 102 | +3. І, нарешті, якщо збігів немає, то, незалежно від наявності прапора `pattern:g`, повертається `null`. |
102 | 103 |
|
103 |
| -3. And, finally, if there are no matches, `null` is returned (doesn't matter if there's flag `pattern:g` or not). |
| 104 | + Це дуже важливий аспект. За відсутності збігів повертається не порожній масив, а саме `null`. Якщо про це забути, можна легко припуститися помилки, наприклад: |
104 | 105 |
|
105 |
| - This a very important nuance. If there are no matches, we don't receive an empty array, but instead receive `null`. Forgetting about that may lead to errors, e.g.: |
| 106 | + ```js run |
| 107 | + let matches = "JavaScript". match(/HTML/); // = null |
| 108 | + if (!matches.length) { // Помилка: у null немає властивості length |
| 109 | + alert("Помилка у рядку вище"); |
| 110 | + } |
| 111 | + ``` |
106 | 112 |
|
107 |
| - ```js run |
108 |
| - let matches = "JavaScript".match(/HTML/); // = null |
| 113 | + Якщо хочеться, щоб результатом завжди був масив, можна написати так: |
109 | 114 |
|
110 |
| - if (!matches.length) { // Error: Cannot read property 'length' of null |
111 |
| - alert("Error in the line above"); |
112 |
| - } |
113 |
| - ``` |
| 115 | + ```js run |
| 116 | + let matches = "JavaScript".match(/HTML/)*!* || []*/!*; |
| 117 | + if (!matches.length) { |
| 118 | + alert("Збігів немає"); // тепер працює |
| 119 | + } |
| 120 | + ``` |
114 | 121 |
|
115 |
| - If we'd like the result to always be an array, we can write it this way: |
| 122 | +## Заміна: str.replace |
116 | 123 |
|
117 |
| - ```js run |
118 |
| - let matches = "JavaScript".match(/HTML/)*!* || []*/!*; |
| 124 | +Метод `str.replace(regexp, replacement)` замінює збіги з `regexp` у рядку `str` на `replacement` (всі збіги, якщо є прапор `pattern:g`, інакше тільки перше). |
119 | 125 |
|
120 |
| - if (!matches.length) { |
121 |
| - alert("No matches"); // now it works |
122 |
| - } |
123 |
| - ``` |
124 |
| - |
125 |
| -## Replacing: str.replace |
126 |
| - |
127 |
| -The method `str.replace(regexp, replacement)` replaces matches found using `regexp` in string `str` with `replacement` (all matches if there's flag `pattern:g`, otherwise, only the first one). |
128 |
| -
|
129 |
| -For instance: |
| 126 | +Наприклад: |
130 | 127 |
|
131 | 128 | ```js run
|
132 |
| -// no flag g |
133 |
| -alert( "We will, we will".replace(/we/i, "I") ); // I will, we will |
| 129 | +// без прапора g |
| 130 | +alert( "Ми будемо, ми будемо".replace(/ми/i, "Я") ); // Я будемо, я будемо |
134 | 131 |
|
135 |
| -// with flag g |
136 |
| -alert( "We will, we will".replace(/we/ig, "I") ); // I will, I will |
| 132 | +// з прапором g |
| 133 | +alert( "Ми будемо, ми будемо".replace(/ми/ig, "Я") ); // Я будемо, Я будемо |
137 | 134 | ```
|
138 | 135 |
|
139 |
| -The second argument is the `replacement` string. We can use special character combinations in it to insert fragments of the match: |
| 136 | +У рядку заміни `replacement` ми можемо використовувати спеціальні комбінації символів для вставки фрагментів збігу: |
140 | 137 |
|
141 |
| -| Symbols | Action in the replacement string | |
| 138 | +| Спецсимволи | Дія у рядку заміни | |
142 | 139 | |--------|--------|
|
143 |
| -|`$&`|inserts the whole match| |
144 |
| -|<code>$`</code>|inserts a part of the string before the match| |
145 |
| -|`$'`|inserts a part of the string after the match| |
146 |
| -|`$n`|if `n` is a 1-2 digit number, then it inserts the contents of n-th parentheses, more about it in the chapter <info:regexp-groups>| |
147 |
| -|`$<name>`|inserts the contents of the parentheses with the given `name`, more about it in the chapter <info:regexp-groups>| |
148 |
| -|`$$`|inserts character `$` | |
| 140 | +|`$&`|вставляє всі знайдені збіги| |
| 141 | +|<code>$`</code>|вставляє частину рядка до збігу| |
| 142 | +|`$'`|вставляє частину рядка після збігу| |
| 143 | +|`$n`|якщо `n` це 1-2 значне число, вставляє вміст n-ї скобочної групи регулярного виразу, більше у розділі <info:regexp-groups>| |
| 144 | +|`$<name>`|вставляє вміст скобочної групи з ім'ям `name`, також вивчимо у розділі <info:regexp-groups>| |
| 145 | +|`$$`|вставляє символ `"$"` | |
149 | 146 |
|
150 |
| -An example with `pattern:$&`: |
| 147 | +Приклад з `pattern:$&`: |
151 | 148 |
|
152 | 149 | ```js run
|
153 |
| -alert( "I love HTML".replace(/HTML/, "$& and JavaScript") ); // I love HTML and JavaScript |
| 150 | +alert( "Люблю HTML".replace(/HTML/, "$& і JavaScript") ); // Люблю HTML і JavaScript |
154 | 151 | ```
|
155 | 152 |
|
156 |
| -## Testing: regexp.test |
| 153 | +## Перевірка: regexp.test |
157 | 154 |
|
158 |
| -The method `regexp.test(str)` looks for at least one match, if found, returns `true`, otherwise `false`. |
| 155 | +Метод `regexp.test(str)` перевіряє, чи є хоч один збіг, якщо так, то повертає `true`, інакше `false`. |
159 | 156 |
|
160 | 157 | ```js run
|
161 |
| -let str = "I love JavaScript"; |
162 |
| -let regexp = /LOVE/i; |
| 158 | +let str = "Я люблю JavaScript"; |
| 159 | +let regexp = /люблю/i; |
163 | 160 |
|
164 | 161 | alert( regexp.test(str) ); // true
|
165 | 162 | ```
|
166 | 163 |
|
167 |
| -Later in this chapter we'll study more regular expressions, walk through more examples, and also meet other methods. |
| 164 | +Далі в цьому розділі ми вивчатимемо регулярні вирази, побачимо ще багато прикладів їх використання, а також познайомимося з іншими методами. |
168 | 165 |
|
169 |
| -Full information about the methods is given in the article <info:regexp-methods>. |
| 166 | +Повна інформація про різні методи наведена в розділі <info:regexp-methods>. |
170 | 167 |
|
171 |
| -## Summary |
| 168 | +## Підсумки |
172 | 169 |
|
173 |
| -- A regular expression consists of a pattern and optional flags: `pattern:g`, `pattern:i`, `pattern:m`, `pattern:u`, `pattern:s`, `pattern:y`. |
174 |
| -- Without flags and special symbols (that we'll study later), the search by a regexp is the same as a substring search. |
175 |
| -- The method `str.match(regexp)` looks for matches: all of them if there's `pattern:g` flag, otherwise, only the first one. |
176 |
| -- The method `str.replace(regexp, replacement)` replaces matches found using `regexp` with `replacement`: all of them if there's `pattern:g` flag, otherwise only the first one. |
177 |
| -- The method `regexp.test(str)` returns `true` if there's at least one match, otherwise, it returns `false`. |
| 170 | +- Регулярний вираз складається з шаблону і необов’язкових прапорів: `pattern:g`, `pattern:i`, `pattern:m`, `pattern:u`, `pattern:s`, `pattern:y`. |
| 171 | +- Без прапорів та спеціальних символів, які ми вивчимо пізніше, пошук за регулярним виразом аналогічний пошуку підрядка. |
| 172 | +- Метод `str.match(regexp)` шукає збіги: всі, якщо є прапор `pattern:g`, інакше тільки перший. |
| 173 | +- Метод `str.replace(regexp, replacement)` замінює збіги з `regexp` на `replacement`: всі, якщо у регулярного виразу є прапор `pattern:g`, інакше тільки перший. |
| 174 | +- Метод `regexp.test(str)` повертає `true`, якщо є хоч один збіг, інакше `false`. |
0 commit comments