diff --git a/9-regular-expressions/14-regexp-lookahead-lookbehind/1-find-non-negative-integers/solution.md b/9-regular-expressions/14-regexp-lookahead-lookbehind/1-find-non-negative-integers/solution.md index ebc12689d..1c9408c67 100644 --- a/9-regular-expressions/14-regexp-lookahead-lookbehind/1-find-non-negative-integers/solution.md +++ b/9-regular-expressions/14-regexp-lookahead-lookbehind/1-find-non-negative-integers/solution.md @@ -1,9 +1,9 @@ -The regexp for an integer number is `pattern:\d+`. +Регулярний вираз для цілого числа `pattern:\d+`. -We can exclude negatives by prepending it with the negative lookbehind: `pattern:(?` tag, we must first find it. We can use the regular expression pattern `pattern:` for that. +Щоб вставити після тегу `` , нам потрібно спершу його знайти. Ми можемо використати для цього регулярний вираз `pattern:`. -In this task we don't need to modify the `` tag. We only need to add the text after it. +в цьому завданні нам не потрібно змінювати тег ``. Нам потрібно тільки додати текст після нього. -Here's how we can do it: +Ось таким чином ми можемо це зробити: ```js run let str = '......'; -str = str.replace(//, '$&

Hello

'); +str = str.replace(//, '$&

Привіт

'); -alert(str); // ...

Hello

... +alert(str); // ...

Привіт

... ``` -In the replacement string `$&` means the match itself, that is, the part of the source text that corresponds to `pattern:`. It gets replaced by itself plus `

Hello

`. +в заміненому рядку `$&` означає співпадіння саме по собі, тобто, частина вихідного тексту яка відповідає шаблону `pattern:`. Її замінено на неї ж плюс `

Привіт

`. -An alternative is to use lookbehind: +Альнернативою було би використання зворотньої перевірки: ```js run let str = '......'; -str = str.replace(/(?<=)/, `

Hello

`); +str = str.replace(/(?<=)/, `

Привіт

`); -alert(str); // ...

Hello

... +alert(str); // ...

Привіт

... ``` -As you can see, there's only lookbehind part in this regexp. +Як бачите, в цьому регулярному виразі є тільки зворотня перевірка. -It works like this: -- At every position in the text. +Це працює таким чином: +- На кожній позиції в тексті. - Check if it's preceeded by `pattern:`. - If it's so then we have the match. diff --git a/9-regular-expressions/14-regexp-lookahead-lookbehind/2-insert-after-head/task.md b/9-regular-expressions/14-regexp-lookahead-lookbehind/2-insert-after-head/task.md index be1a259f6..05b42daf7 100644 --- a/9-regular-expressions/14-regexp-lookahead-lookbehind/2-insert-after-head/task.md +++ b/9-regular-expressions/14-regexp-lookahead-lookbehind/2-insert-after-head/task.md @@ -1,13 +1,13 @@ -# Insert After Head +# Вставка після Head -We have a string with an HTML Document. +У нас є рядок з HTML-документом. -Write a regular expression that inserts `

Hello

` immediately after `` tag. The tag may have attributes. +Напишіть регулярний вираз який вставляє `

Привіт

` одразу після тегу ``. Тег може мати атрибути. -For instance: +Приклад: ```js -let regexp = /your regular expression/; +let regexp = /ваш регулярний вираз/; let str = ` @@ -17,13 +17,13 @@ let str = ` `; -str = str.replace(regexp, `

Hello

`); +str = str.replace(regexp, `

Привіт

`); ``` -After that the value of `str` should be: +Після цього значення `str` має бути: ```html -

Hello

+

Привіт

... diff --git a/9-regular-expressions/14-regexp-lookahead-lookbehind/article.md b/9-regular-expressions/14-regexp-lookahead-lookbehind/article.md index cee8215f9..d6dd00cfe 100644 --- a/9-regular-expressions/14-regexp-lookahead-lookbehind/article.md +++ b/9-regular-expressions/14-regexp-lookahead-lookbehind/article.md @@ -1,134 +1,134 @@ -# Lookahead and lookbehind +# Перевірка уперед та назад -Sometimes we need to find only those matches for a pattern that are followed or preceded by another pattern. +Іноді, нам потрібно знайти тільки такі співпадіння з шаблоном, за якими слідує, або яким передує інший шаблон. -There's a special syntax for that, called "lookahead" and "lookbehind", together referred to as "lookaround". +Для цього існують спеціальні синтаксичні конструкції, котрі називається "перевірка уперед" та "перевірка назад". -For the start, let's find the price from the string like `subject:1 turkey costs 30€`. That is: a number, followed by `subject:€` sign. +Для початку, давайте знайдемо ціну у рядку `subject:1 індичка коштує 30€`. Маємо: число, за яким йде символ `subject:€`. -## Lookahead +## Перевірка уперед -The syntax is: `pattern:X(?=Y)`, it means "look for `pattern:X`, but match only if followed by `pattern:Y`". There may be any pattern instead of `pattern:X` and `pattern:Y`. +Синтаксис виглядає наступнм чином: `pattern:X(?=Y)`, це означає "шукай `pattern:X`, але вважай його співпадінням, тільки якщо за ним слідує `pattern:Y`". Замість `pattern:X` та `pattern:Y` можуть бути будь-які інші шаблони. -For an integer number followed by `subject:€`, the regexp will be `pattern:\d+(?=€)`: +Для цілого числа, за яким слідує `subject:€`, регулярний вираз виглядатиме наступним чином `pattern:\d+(?=€)`: ```js run -let str = "1 turkey costs 30€"; +let str = "1 індичка коштує 30€"; -alert( str.match(/\d+(?=€)/) ); // 30, the number 1 is ignored, as it's not followed by € +alert( str.match(/\d+(?=€)/) ); // 30, число 1 ігнорується, оскільки після нього не стоїть символ € ``` -Please note: the lookahead is merely a test, the contents of the parentheses `pattern:(?=...)` is not included in the result `match:30`. +Зверніть увагу: перевірка уперед це свого роду тест, вміст в дужках `pattern:(?=...)` не входить до відображуваного регулярним виразом співпадіння `match:30`. -When we look for `pattern:X(?=Y)`, the regular expression engine finds `pattern:X` and then checks if there's `pattern:Y` immediately after it. If it's not so, then the potential match is skipped, and the search continues. +Коли ми шукаємо `pattern:X(?=Y)`, регулярний вираз знаходить `pattern:X` і далі перевіряє наявність `pattern:Y` одразу після нього. Якщо це не так, тоді потенційне співпадіння пропускається і регулярний вираз продовжує пошук. -More complex tests are possible, e.g. `pattern:X(?=Y)(?=Z)` means: +Можливі і більш складні тести, наприклад `pattern:X(?=Y)(?=Z)` означає: -1. Find `pattern:X`. -2. Check if `pattern:Y` is immediately after `pattern:X` (skip if isn't). -3. Check if `pattern:Z` is also immediately after `pattern:X` (skip if isn't). -4. If both tests passed, then the `pattern:X` is a match, otherwise continue searching. +1. Знайди `pattern:X`. +2. Перевір, чи `pattern:Y` йде одразу після `pattern:X` (пропускай, якщо це не так). +3. Перевір, чи `pattern:Z` також йде одразу після `pattern:X` (пропускай, якщо це не так). +4. Якщо обидва тести пройдено, тоді `pattern:X` відповідає умовам пошуку, в інщому випадку -- продовжуй пошук. -In other words, such pattern means that we're looking for `pattern:X` followed by `pattern:Y` and `pattern:Z` at the same time. +Інакше кажучи, такий шаблон означає, що ми шукаємо на `pattern:X` за яким одночасно слідують `pattern:Y` та `pattern:Z`. -That's only possible if patterns `pattern:Y` and `pattern:Z` aren't mutually exclusive. +Це можливо тільки за умови, якщо шаблон `pattern:Y` та `pattern:Z` не виключають один одного. -For example, `pattern:\d+(?=\s)(?=.*30)` looks for `pattern:\d+` that is followed by a space `pattern:(?=\s)`, and there's `30` somewhere after it `pattern:(?=.*30)`: +Наприклад, `pattern:\d+(?=\s)(?=.*30)` шукає на `pattern:\d+` за яким йде пробільний символ `pattern:(?=\s)`, а також `30` десь після нього `pattern:(?=.*30)`: ```js run -let str = "1 turkey costs 30€"; +let str = "1 індичка коштує 30€"; alert( str.match(/\d+(?=\s)(?=.*30)/) ); // 1 ``` -In our string that exactly matches the number `1`. +В нашому рядку цим параметрам повністю відповідає число `1`. -## Negative lookahead +## Негативна перевірка уперед -Let's say that we want a quantity instead, not a price from the same string. That's a number `pattern:\d+`, NOT followed by `subject:€`. +Скажімо, ми хочем знайти кількість, а не ціну в тому самому рядку. Тобто, шукаємо число `pattern:\d+`, за якийм НЕ слідує `subject:€`. -For that, a negative lookahead can be applied. +В такому випадку, доречним буде використання негативної перевірки уперед. -The syntax is: `pattern:X(?!Y)`, it means "search `pattern:X`, but only if not followed by `pattern:Y`". +Синтаксис виглядає наступним чином: `pattern:X(?!Y)`, і означає "шукай `pattern:X`, але за умови, що після нього не йде `pattern:Y`". ```js run -let str = "2 turkeys cost 60€"; +let str = "2 індички коштують 60€"; -alert( str.match(/\d+\b(?!€)/g) ); // 2 (the price is not matched) +alert( str.match(/\d+\b(?!€)/g) ); // 2 (ціна не відповідає вимогам шаблону і не відображається в результаті) ``` -## Lookbehind +## Перевірка назад -```warn header="Lookbehind browser compatibility" -Please Note: Lookbehind is not supported in non-V8 browsers, such as Safari, Internet Explorer. +```warn header="Сумісність браузерів з перевіркою назад" +Зверніть увагу: Перевірка назад не підтримується в браузерах з відміннимим від V8 двигунами, зокрема Safari, Internet Explorer. ``` -Lookahead allows to add a condition for "what follows". +Перевірка уперед дозволяє додати умову на кшталт "те, що слідує після". -Lookbehind is similar, but it looks behind. That is, it allows to match a pattern only if there's something before it. +Перевірка назад подібна, але дивиться у зворотньому напрямку. Таким чином, вона видає результат, тільки якщо співпадає і шаблон і те, що йде до нього. -The syntax is: -- Positive lookbehind: `pattern:(?<=Y)X`, matches `pattern:X`, but only if there's `pattern:Y` before it. -- Negative lookbehind: `pattern:(?