Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
418ca73
9-regular-expressions/09-regexp-groups
keslo May 31, 2019
c976c08
Update article.md
keslo May 31, 2019
a7b707f
Update article.md
keslo May 31, 2019
73d9d16
Update article.md
keslo Jun 9, 2019
7e8cf03
Update article.md
keslo Jun 9, 2019
b189e22
Update article.md
keslo Jun 9, 2019
5514fae
Update article.md
keslo Jun 10, 2019
efb2159
Update solution.md
keslo Jun 10, 2019
ce60cc2
Update task.md
keslo Jun 13, 2019
0bb446f
Update solution.md
keslo Jun 17, 2019
1a08335
Update task.md
keslo Jun 18, 2019
602f794
Update solution.md
keslo Jun 18, 2019
c4f9c0f
Update task.md
keslo Jun 18, 2019
78b1918
Update solution.md
keslo Jun 18, 2019
e4dc2dc
Update task.md
keslo Jun 18, 2019
7e9f49e
Update article.md
keslo Jun 24, 2019
57061e8
Update solution.md
keslo Jun 24, 2019
909b88d
Update solution.md
keslo Jun 24, 2019
bcdab02
Update task.md
keslo Jun 24, 2019
354b84a
Update solution.md
keslo Jun 24, 2019
e504b62
Update task.md
keslo Jun 24, 2019
e57098d
Update task.md
keslo Jun 24, 2019
7de8bb6
Update solution.md
keslo Jun 24, 2019
d70a583
Update task.md
keslo Jun 24, 2019
e4c8a99
Update solution.md
keslo Jun 24, 2019
97f1a92
Update article.md
keslo Jun 24, 2019
c1a58da
Update solution.md
keslo Jun 25, 2019
bb076a1
Update task.md
keslo Jun 25, 2019
1f7421a
Update task.md
keslo Jun 25, 2019
73590f9
Update solution.md
keslo Jun 25, 2019
07fcbd8
Update article.md
keslo Jun 25, 2019
70a75f6
Update article.md
keslo Jun 25, 2019
af77e1e
Update article.md
keslo Jun 25, 2019
be3de96
Update article.md
keslo Jun 27, 2019
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
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. Either we have them or we don't.
Мы можем задать ещё ровно 3 дополнительных шестнадцатеричных цифры. Нам не нужно больше или меньше - в цвете либо 3, либо 6 цифр.

The simplest way to add them -- is to append to the regexp: `pattern:/#[a-f0-9]{3}([a-f0-9]{3})?/i`
Простейший способ добавить их -- добавить в регулярное выражение: `pattern:/#[a-f0-9]{3}([a-f0-9]{3})?/i`

We can do it in a smarter way though: `pattern:/#([a-f0-9]{3}){1,2}/i`.
Мы можем сделать это более интересным способом: `pattern:/#([a-f0-9]{3}){1,2}/i`.

Here the regexp `pattern:[a-f0-9]{3}` is in parentheses to apply the quantifier `pattern:{1,2}` to it as a whole.
Регулярное выражение `pattern:[a-f0-9]{3}` заключено в скобки для корректного применения к нему квантификатора `pattern:{1,2}`.

In action:
В действии:

```js run
let reg = /#([a-f0-9]{3}){1,2}/gi;
Expand All @@ -18,7 +18,7 @@ let str = "color: #3f3; background-color: #AA00ef; and: #abcd";
alert( str.match(reg) ); // #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 reg = /#([a-f0-9]{3}){1,2}\b/gi;
Expand Down
Original file line number Diff line number Diff line change
@@ -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 reg = /your regexp/g;
let reg = /ваш регэксп/g;

let str = "color: #3f3; background-color: #AA00ef; and: #abcd";

alert( str.match(reg) ); // #3f3 #AA00ef
```

P.S. This should be exactly 3 or 6 hex digits: values like `#abcd` should not match.
P.S. Это должно быть ровно 3 или 6 шестнадцатеричных цифр. При этом значения типа `#abcd` не должны совпадать в результат.
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@

An non-negative integer number is `pattern:\d+`. We should exclude `0` as the first digit, as we don't need zero, but we can allow it in further digits.
Регулярное выражение для неотрицательного целого числа `pattern:\d+`. Мы должны исключить `0` в качестве первой цифры, так как нам не нужен ноль, но мы можем разрешить его появление далее.

So that gives us `pattern:[1-9]\d*`.
Нам позволит сделать это регулярное выражение: `pattern:[1-9]\d*`.

A decimal part is: `pattern:\.\d+`.
Десятичная часть находится с помощью: `pattern:\.\d+`.

Because the decimal part is optional, let's put it in parentheses with the quantifier `pattern:'?'`.
Поскольку десятичная часть является необязательной, то давайте заключим ее в скобки с квантификатором `pattern:'?'`.

Finally we have the regexp: `pattern:[1-9]\d*(\.\d+)?`:
В итоге, мы получаем регулярное выражение: `pattern:[1-9]\d*(\.\d+)?`:

```js run
let reg = /[1-9]\d*(\.\d+)?/g;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
# Find positive numbers
# Найти положительные числа

Create a regexp that looks for positive numbers, including those without a decimal point.
Создайте регулярное выражение, которое ищет положительные числа, включая числа без десятичной части.

An example of use:
Пример использования:
```js
let reg = /your regexp/g;
let reg = /ваш регэксп/g;

let str = "1.5 0 -5 12. 123.4.";

alert( str.match(reg) ); // 1.5, 12, 123.4 (ignores 0 and -5)
alert( str.match(reg) ); // 1.5, 12, 123.4 (игнорирует 0 и -5)
```
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
A positive number with an optional decimal part is (per previous task): `pattern:\d+(\.\d+)?`.
Положительное число с необязательным присутствием десятичной части (из прошлой задачи): `pattern:\d+(\.\d+)?`.

Let's add an optional `-` in the beginning:
Давайте добавим необязательный `-` в начало:

```js run
let reg = /-?\d+(\.\d+)?/g;
Expand Down
Original file line number Diff line number Diff line change
@@ -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 reg = /your regexp/g;
let reg = /ваше выражение/g;

let str = "-1.5 0 2 -123.4.";

Expand Down
Original file line number Diff line number Diff line change
@@ -1,39 +1,39 @@
A regexp for a number is: `pattern:-?\d+(\.\d+)?`. We created it in previous tasks.
Регулярное выражение для числа: `pattern:-?\d+(\.\d+)?`. Мы создали его в предыдущих задачах.

An operator is `pattern:[-+*/]`. We put the dash `pattern:-` first, because in the middle it would mean a character range, we don't need that.
Регулярное выражение для оператора `pattern:[-+*/]`. Мы вставили тире `pattern:-` в начало выражения, потому что в середине этот символ будет означать диапазон, а нам это не нужно.

Note that a slash should be escaped inside a JavaScript regexp `pattern:/.../`.
Отметим, что косая черта должна быть экранирована внутри регулярного выражения 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+)?`.

To get a result as an array let's put parentheses around the data that we need: numbers and the operator: `pattern:(-?\d+(\.\d+)?)\s*([-+*/])\s*(-?\d+(\.\d+)?)`.
Для получения результата в виде массива давайте вставим скобки вокруг данных, которые нам необходимы: чисел и операторов: `pattern:(-?\d+(\.\d+)?)\s*([-+*/])\s*(-?\d+(\.\d+)?)`.

In action:
В действии:

```js run
let reg = /(-?\d+(\.\d+)?)\s*([-+*\/])\s*(-?\d+(\.\d+)?)/;

alert( "1.2 + 12".match(reg) );
```

The result includes:
Результат `result` включает в себя:

- `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.
Нам необходимы только числа и оператор без полного совпадения или десятичной части.

The full match (the arrays first item) can be removed by shifting the array `pattern:result.shift()`.
Полное совпадение (первый элемент массива) может быть удален при помощи сдвига массива `pattern:result.shift()`.

The decimal groups can be removed by making them into non-capturing groups, by adding `pattern:?:` to the beginning: `pattern:(?:\.\d+)?`.
От десятичных групп можно избавиться, если исключить захват скобочной группы, добавив `pattern:?:` в начало: `pattern:(?:\.\d+)?`.

The final solution:
Итоговое решение:

```js run
function parse(expr) {
Expand Down
Original file line number Diff line number Diff line change
@@ -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)`, которая принимает выражение и возвращает массив из трёх элементов:

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");
Expand Down
Loading