diff --git a/9-regular-expressions/11-regexp-groups/01-test-mac/solution.md b/9-regular-expressions/11-regexp-groups/01-test-mac/solution.md index f7a5f1e39..c85b604a8 100644 --- a/9-regular-expressions/11-regexp-groups/01-test-mac/solution.md +++ b/9-regular-expressions/11-regexp-groups/01-test-mac/solution.md @@ -1,21 +1,21 @@ -A two-digit hex number is `pattern:[0-9a-f]{2}` (assuming the flag `pattern:i` is set). +Двоцифрове шістнадцяткове число можна записати як `pattern:[0-9a-f]{2}`(припустивши, що задано прапорець `pattern:i`). -We need that number `NN`, and then `:NN` repeated 5 times (more numbers); +Нам потрібно число `NN`, а за ним `:NN`, повторене 5 разів (більше чисел); -The regexp is: `pattern:[0-9a-f]{2}(:[0-9a-f]{2}){5}` +Регулярний вираз: `pattern:[0-9a-f]{2}(:[0-9a-f]{2}){5}` -Now let's show that the match should capture all the text: start at the beginning and end at the end. That's done by wrapping the pattern in `pattern:^...$`. +Тепер продемонструємо, що збіг має захоплювати весь текст: з самого початку до самого кінця. Робиться це через огортання виразу в `pattern:^...$`. -Finally: +В підсумку: ```js run let regexp = /^[0-9a-f]{2}(:[0-9a-f]{2}){5}$/i; alert( regexp.test('01:32:54:67:89:AB') ); // true -alert( regexp.test('0132546789AB') ); // false (no colons) +alert( regexp.test('0132546789AB') ); // false (без двокрапок) -alert( regexp.test('01:32:54:67:89') ); // false (5 numbers, need 6) +alert( regexp.test('01:32:54:67:89') ); // false (5 чисел, має бути 6) -alert( regexp.test('01:32:54:67:89:ZZ') ) // false (ZZ in the end) +alert( regexp.test('01:32:54:67:89:ZZ') ) // false (ZZ в кінці) ``` diff --git a/9-regular-expressions/11-regexp-groups/01-test-mac/task.md b/9-regular-expressions/11-regexp-groups/01-test-mac/task.md index a2e799cfa..ebfa82c04 100644 --- a/9-regular-expressions/11-regexp-groups/01-test-mac/task.md +++ b/9-regular-expressions/11-regexp-groups/01-test-mac/task.md @@ -1,20 +1,20 @@ -# Check MAC-address +# Перевірити MAC-адресу -[MAC-address](https://en.wikipedia.org/wiki/MAC_address) of a network interface consists of 6 two-digit hex numbers separated by a colon. +[MAC-адреса](https://uk.wikipedia.org/wiki/MAC-адреса) мережевого інтерфейсу складається з 6 двоцифрових шістнадцяткових чисел, розділених двокрапкою. -For instance: `subject:'01:32:54:67:89:AB'`. +Наприклад: `subject:'01:32:54:67:89:AB'`. -Write a regexp that checks whether a string is MAC-address. +Напишіть регулярний вираз, який перевіряє, чи є рядок MAC-адресою. -Usage: +Приклад використання: ```js -let regexp = /your regexp/; +let regexp = /ваш регулярний вираз/; alert( regexp.test('01:32:54:67:89:AB') ); // true -alert( regexp.test('0132546789AB') ); // false (no colons) +alert( regexp.test('0132546789AB') ); // false (без двокрапок) -alert( regexp.test('01:32:54:67:89') ); // false (5 numbers, must be 6) +alert( regexp.test('01:32:54:67:89') ); // false (5 чисел, має бути 6) -alert( regexp.test('01:32:54:67:89:ZZ') ) // false (ZZ at the end) +alert( regexp.test('01:32:54:67:89:ZZ') ) // false (ZZ в кінці) ``` diff --git a/9-regular-expressions/11-regexp-groups/02-find-webcolor-3-or-6/solution.md b/9-regular-expressions/11-regexp-groups/02-find-webcolor-3-or-6/solution.md index 0806dc4fd..122146510 100644 --- a/9-regular-expressions/11-regexp-groups/02-find-webcolor-3-or-6/solution.md +++ b/9-regular-expressions/11-regexp-groups/02-find-webcolor-3-or-6/solution.md @@ -1,12 +1,12 @@ -A regexp to search 3-digit color `#abc`: `pattern:/#[a-f0-9]{3}/i`. +Регулярний вираз для пошуку тризначного коду кольору `#abc`: `pattern:/#[a-f0-9]{3}/i`. -We can add exactly 3 more optional hex digits. We don't need more or less. The color has either 3 or 6 digits. +Ми можемо додати рівно 3 додаткові шістнадцяткові цифри, не більше й не менше. Колір містить 3 або 6 цифр. -Let's use the quantifier `pattern:{1,2}` for that: we'll have `pattern:/#([a-f0-9]{3}){1,2}/i`. +Використаємо для цього квантифікатор `pattern:{1,2}`: отримаємо `pattern:/#([a-f0-9]{3}){1,2}/i`. -Here the pattern `pattern:[a-f0-9]{3}` is enclosed in parentheses to apply the quantifier `pattern:{1,2}`. +В цьому випадку, шаблон `pattern:[a-f0-9]{3}` оточений дужками для застосування квантифікатора `pattern:{1,2}`. -In action: +Код у дії: ```js run let regexp = /#([a-f0-9]{3}){1,2}/gi; @@ -16,7 +16,7 @@ let str = "color: #3f3; background-color: #AA00ef; and: #abcd"; alert( str.match(regexp) ); // #3f3 #AA00ef #abc ``` -There's a minor problem here: the pattern found `match:#abc` in `subject:#abcd`. To prevent that we can add `pattern:\b` to the end: +Бачимо невелику проблему: вираз знайшов `match:#abc` в `subject:#abcd`. Для запобігання цьому, додамо в кінці `pattern:\b`: ```js run let regexp = /#([a-f0-9]{3}){1,2}\b/gi; diff --git a/9-regular-expressions/11-regexp-groups/02-find-webcolor-3-or-6/task.md b/9-regular-expressions/11-regexp-groups/02-find-webcolor-3-or-6/task.md index 09108484a..603144933 100644 --- a/9-regular-expressions/11-regexp-groups/02-find-webcolor-3-or-6/task.md +++ b/9-regular-expressions/11-regexp-groups/02-find-webcolor-3-or-6/task.md @@ -1,14 +1,14 @@ -# Find color in the format #abc or #abcdef +# Знайти колір у форматі #abc або #abcdef -Write a RegExp that matches colors in the format `#abc` or `#abcdef`. That is: `#` followed by 3 or 6 hexadecimal digits. +Напишіть регулярний вираз, що знаходить збіг по кольорам у форматі `#abc` або `#abcdef`. Формула є наступною: `#`, за яким знаходяться 3 або 6 шістнадцяткових цифр. -Usage example: +Приклад використання: ```js -let regexp = /your regexp/g; +let regexp = /ваш регулярний вираз/g; let str = "color: #3f3; background-color: #AA00ef; and: #abcd"; alert( str.match(regexp) ); // #3f3 #AA00ef ``` -P.S. This should be exactly 3 or 6 hex digits. Values with 4 digits, such as `#abcd`, should not match. +P.S. Має бути саме 3 або 6 шістнадцяткових цифр. Значення з 4 цифрами, такі як `#abcd`, не мають рахуватись за збіг. diff --git a/9-regular-expressions/11-regexp-groups/03-find-decimal-numbers/solution.md b/9-regular-expressions/11-regexp-groups/03-find-decimal-numbers/solution.md index 813d619ef..4abbbd407 100644 --- a/9-regular-expressions/11-regexp-groups/03-find-decimal-numbers/solution.md +++ b/9-regular-expressions/11-regexp-groups/03-find-decimal-numbers/solution.md @@ -1,6 +1,6 @@ -A positive number with an optional decimal part is: `pattern:\d+(\.\d+)?`. +Додатне число з необов’язковою десятковою частиною: `pattern:\d+(\.\d+)?`. -Let's add the optional `pattern:-` in the beginning: +Додамо необов’язковий `pattern:-` на початку: ```js run let regexp = /-?\d+(\.\d+)?/g; diff --git a/9-regular-expressions/11-regexp-groups/03-find-decimal-numbers/task.md b/9-regular-expressions/11-regexp-groups/03-find-decimal-numbers/task.md index 4f5a73fff..e5744ca44 100644 --- a/9-regular-expressions/11-regexp-groups/03-find-decimal-numbers/task.md +++ b/9-regular-expressions/11-regexp-groups/03-find-decimal-numbers/task.md @@ -1,11 +1,11 @@ -# Find all numbers +# Знайти всі числа -Write a regexp that looks for all decimal numbers including integer ones, with the floating point and negative ones. +Напишіть регулярний вираз, який шукатиме всі десяткові числа, включно з числами цілими, з плаваючою комою та від’ємними. -An example of use: +Приклад використання: ```js -let regexp = /your regexp/g; +let regexp = /ваш регулярний вираз/g; let str = "-1.5 0 2 -123.4."; diff --git a/9-regular-expressions/11-regexp-groups/04-parse-expression/solution.md b/9-regular-expressions/11-regexp-groups/04-parse-expression/solution.md index ac67519bb..ed5526628 100644 --- a/9-regular-expressions/11-regexp-groups/04-parse-expression/solution.md +++ b/9-regular-expressions/11-regexp-groups/04-parse-expression/solution.md @@ -1,21 +1,21 @@ -A regexp for a number is: `pattern:-?\d+(\.\d+)?`. We created it in the previous task. +Регулярний вираз для числа є наступним: `pattern:-?\d+(\.\d+)?`. Його ми створили в рамках попередньої задачі. -An operator is `pattern:[-+*/]`. The hyphen `pattern:-` goes first in the square brackets, because in the middle it would mean a character range, while we just want a character `-`. +Оператором слугуватиме `pattern:[-+*/]`. Дефіс `pattern:-` стоїть першим в квадратних дужках, бо позиція посередині означає діапазон знаків, тоді як нам потрібен лише `-`. -The slash `/` should be escaped inside a JavaScript regexp `pattern:/.../`, we'll do that later. +Символ `/` має бути екранованим всередині регулярного виразу JavaScript `pattern:/.../`, зробимо це потім. -We need a number, an operator, and then another number. And optional spaces between them. +Нам потрібне число, оператор, тоді ще одне число. Та можливі пробіли між ними. -The full regular expression: `pattern:-?\d+(\.\d+)?\s*[-+*/]\s*-?\d+(\.\d+)?`. +Повний регулярний вираз: `pattern:-?\d+(\.\d+)?\s*[-+*/]\s*-?\d+(\.\d+)?`. -It has 3 parts, with `pattern:\s*` between them: -1. `pattern:-?\d+(\.\d+)?` - the first number, -1. `pattern:[-+*/]` - the operator, -1. `pattern:-?\d+(\.\d+)?` - the second number. +Він містить 3 частини, з `pattern:\s*` між ними: +1. `pattern:-?\d+(\.\d+)?` - перше число, +1. `pattern:[-+*/]` - оператор, +1. `pattern:-?\d+(\.\d+)?` - друге число. -To make each of these parts a separate element of the result array, let's enclose them in parentheses: `pattern:(-?\d+(\.\d+)?)\s*([-+*/])\s*(-?\d+(\.\d+)?)`. +Аби зробити кожну з цих частин окремим елементом масиву результатів, помістимо їх в круглі дужки: `pattern:(-?\d+(\.\d+)?)\s*([-+*/])\s*(-?\d+(\.\d+)?)`. -In action: +Код у дії: ```js run let regexp = /(-?\d+(\.\d+)?)\s*([-+*\/])\s*(-?\d+(\.\d+)?)/; @@ -23,22 +23,22 @@ let regexp = /(-?\d+(\.\d+)?)\s*([-+*\/])\s*(-?\d+(\.\d+)?)/; alert( "1.2 + 12".match(regexp) ); ``` -The result includes: +Розглянемо результат: -- `result[0] == "1.2 + 12"` (full match) -- `result[1] == "1.2"` (first group `(-?\d+(\.\d+)?)` -- the first number, including the decimal part) -- `result[2] == ".2"` (second group`(\.\d+)?` -- the first decimal part) -- `result[3] == "+"` (third group `([-+*\/])` -- the operator) -- `result[4] == "12"` (forth group `(-?\d+(\.\d+)?)` -- the second number) -- `result[5] == undefined` (fifth group `(\.\d+)?` -- the last decimal part is absent, so it's undefined) +- `result[0] == "1.2 + 12"` (повний збіг) +- `result[1] == "1.2"` (перша група `(-?\d+(\.\d+)?)` -- перше число, включаючи десяткову частину) +- `result[2] == ".2"` (друга група `(\.\d+)?` -- перша десяткова частина) +- `result[3] == "+"` (третя група `([-+*\/])` -- оператор) +- `result[4] == "12"` (четверта група `(-?\d+(\.\d+)?)` -- друге число) +- `result[5] == undefined` (п’ята група `(\.\d+)?` -- остання десяткова частина відсутня, тому вона undefined) -We only want the numbers and the operator, without the full match or the decimal parts, so let's "clean" the result a bit. +Нам потрібні лише числа та оператор, без повного збігу чи десяткових частин, тож проведемо невелику "чистку" результату. -The full match (the arrays first item) can be removed by shifting the array `result.shift()`. +Повний збіг (перший елемент масиву) можна прибрати методом масиву `result.shift()`. -Groups that contain decimal parts (number 2 and 4) `pattern:(.\d+)` can be excluded by adding `pattern:?:` to the beginning: `pattern:(?:\.\d+)?`. +Групи 2 та 5, що містять десяткові частини `pattern:(.\d+)`, можна оминути, додавши `pattern:?:` на початку: `pattern:(?:\.\d+)?`. -The final solution: +Кінцевий варіант: ```js run function parse(expr) { diff --git a/9-regular-expressions/11-regexp-groups/04-parse-expression/task.md b/9-regular-expressions/11-regexp-groups/04-parse-expression/task.md index 8b54d4683..a84860ce5 100644 --- a/9-regular-expressions/11-regexp-groups/04-parse-expression/task.md +++ b/9-regular-expressions/11-regexp-groups/04-parse-expression/task.md @@ -1,23 +1,23 @@ -# Parse an expression +# Розберіть вираз -An arithmetical expression consists of 2 numbers and an operator between them, for instance: +Арифметичний вираз складається з двох чисел та оператору між ними, наприклад: - `1 + 2` - `1.2 * 3.4` - `-3 / -6` - `-2 - 2` -The operator is one of: `"+"`, `"-"`, `"*"` or `"/"`. +Оператором може бути: `"+"`, `"-"`, `"*"` або `"/"`. -There may be extra spaces at the beginning, at the end or between the parts. +Додаткові пробіли можуть бути на початку, в кінці чи всередині виразу. -Create a function `parse(expr)` that takes an expression and returns an array of 3 items: +Напишіть функцію `parse(expr)`, яка приймає вираз та повертає масив з 3-ьох елементів: -1. The first number. -2. The operator. -3. The second number. +1. Перше число. +2. Оператор. +3. Друге число. -For example: +Наприклад: ```js let [a, op, b] = parse("1.2 * 3.4"); diff --git a/9-regular-expressions/11-regexp-groups/article.md b/9-regular-expressions/11-regexp-groups/article.md index 796e23f54..a870060cc 100644 --- a/9-regular-expressions/11-regexp-groups/article.md +++ b/9-regular-expressions/11-regexp-groups/article.md @@ -1,31 +1,31 @@ -# Capturing groups +# Групи захоплення -A part of a pattern can be enclosed in parentheses `pattern:(...)`. This is called a "capturing group". +Частину виразу можна обгорнути в круглі дужки `pattern:(...)`. Це називається "група захоплення". -That has two effects: +Такий прийом має два наслідки: -1. It allows to get a part of the match as a separate item in the result array. -2. If we put a quantifier after the parentheses, it applies to the parentheses as a whole. +1. Він дозволяє отримати частину збігу в якості окремого елементу в масиві результатів. +2. Якщо ми поставимо квантифікатор після дужок, він застосується до всього їх вмісту. -## Examples +## Приклади -Let's see how parentheses work in examples. +Розглянемо як працюють круглі дужки на прикладах. -### Example: gogogo +### Приклад: gogogo -Without parentheses, the pattern `pattern:go+` means `subject:g` character, followed by `subject:o` repeated one or more times. For instance, `match:goooo` or `match:gooooooooo`. +Без круглих дужок, вираз `pattern:go+` означає символ `subject:g`, за яким слідує `subject:o` на повторі один чи кілька разів. Тобто, `match:goooo` чи `match:gooooooooo`. -Parentheses group characters together, so `pattern:(go)+` means `match:go`, `match:gogo`, `match:gogogo` and so on. +Круглі дужки об’єднують символи в групи, тож `pattern:(go)+` означає `match:go`, `match:gogo`, `match:gogogo` і так далі. ```js run alert( 'Gogogo now!'.match(/(go)+/ig) ); // "Gogogo" ``` -### Example: domain +### Приклад: домен -Let's make something more complex -- a regular expression to search for a website domain. +Зробимо дещо складніше -- регулярний вираз для пошуку домену сайту. -For example: +Наприклад: ``` mail.com @@ -33,9 +33,9 @@ users.mail.com smith.users.mail.com ``` -As we can see, a domain consists of repeated words, a dot after each one except the last one. +Як бачимо, домен складається з повторюваних слів та крапки після кожного з них (окрім останнього). -In regular expressions that's `pattern:(\w+\.)+\w+`: +В регулярних виразах це `pattern:(\w+\.)+\w+`: ```js run let regexp = /(\w+\.)+\w+/g; @@ -43,17 +43,17 @@ let regexp = /(\w+\.)+\w+/g; alert( "site.com my.site.com".match(regexp) ); // site.com,my.site.com ``` -The search works, but the pattern can't match a domain with a hyphen, e.g. `my-site.com`, because the hyphen does not belong to class `pattern:\w`. +Пошук працює, але патерн не збігатиметься з доменом з дефісом: наприклад, `my-site.com`, бо дефіс не належить до класу `pattern:\w`. -We can fix it by replacing `pattern:\w` with `pattern:[\w-]` in every word except the last one: `pattern:([\w-]+\.)+\w+`. +Ми можемо виправити це, замінивши `pattern:\w` на `pattern:[\w-]` в кожному слові (окрім останнього): `pattern:([\w-]+\.)+\w+`. -### Example: email +### Приклад: email -The previous example can be extended. We can create a regular expression for emails based on it. +Попередній приклад можна розширити. Спираючись на нього, ми можемо створити регулярний вираз для адрес електронної пошти. -The email format is: `name@domain`. Any word can be the name, hyphens and dots are allowed. In regular expressions that's `pattern:[-.\w]+`. +Формат електронної пошти: `name@domain`. Name може бути будь-яким словом, дефіси та крапки допускаються. В регулярних виразах це `pattern:[-.\w]+`. -The pattern: +Вираз є наступним: ```js run let regexp = /[-.\w]+@([\w-]+\.)+[\w-]+/g; @@ -61,27 +61,27 @@ let regexp = /[-.\w]+@([\w-]+\.)+[\w-]+/g; alert("my@mail.com @ his@site.com.uk".match(regexp)); // my@mail.com, his@site.com.uk ``` -That regexp is not perfect, but mostly works and helps to fix accidental mistypes. The only truly reliable check for an email can only be done by sending a letter. +Це неідеальний регулярний вираз, але здебільшого робочий та здатний виправити випадкові помилки. Єдина справді надійна перевірка електронної пошти -- відправка листа. -## Parentheses contents in the match +## Вміст дужок всередині збігу -Parentheses are numbered from left to right. The search engine memorizes the content matched by each of them and allows to get it in the result. +Дужки нумеруються зліва направо. Пошукова система запам'ятовує вміст збігу для кожної з них та дозволяє отримати його всередині результату. -The method `str.match(regexp)`, if `regexp` has no flag `g`, looks for the first match and returns it as an array: +У випадку, якщо `regexp` не містить прапорця `g`, метод `str.match(regexp)` шукає перший збіг та повертає його як масив: -1. At index `0`: the full match. -2. At index `1`: the contents of the first parentheses. -3. At index `2`: the contents of the second parentheses. -4. ...and so on... +1. Індекс `0`: повний збіг. +2. Індекс `1`: вміст перших дужок. +3. Індекс `2`: вміст других дужок. +4. ...і так далі... -For instance, we'd like to find HTML tags `pattern:<.*?>`, and process them. It would be convenient to have tag content (what's inside the angles), in a separate variable. +Для прикладу, ми б хотіли знайти HTML теги `pattern:<.*?>` та обробити їх. Було б зручно мати вміст тегу (все, що всередині кутових дужок) в окремій змінній. -Let's wrap the inner content into parentheses, like this: `pattern:<(.*?)>`. +Огорнемо внутрішній вміст у круглі дужки, ось так: `pattern:<(.*?)>`. -Now we'll get both the tag as a whole `match: