Skip to content

Commit 1e2b09b

Browse files
committed
up
1 parent 91e4c89 commit 1e2b09b

File tree

12 files changed

+156
-100
lines changed

12 files changed

+156
-100
lines changed

10-regular-expressions-javascript/10-regexp-backreferences/1-find-matching-bbtags/solution.md

Lines changed: 0 additions & 20 deletions
This file was deleted.

10-regular-expressions-javascript/10-regexp-backreferences/1-find-matching-bbtags/task.md

Lines changed: 0 additions & 41 deletions
This file was deleted.
Lines changed: 27 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,63 +1,62 @@
1-
# Обратные ссылки: \n и $n
1+
# Backreferences: \n and $n
22

3-
Скобочные группы можно не только получать в результате.
4-
5-
Движок регулярных выражений запоминает их содержимое, и затем его можно использовать как в самом паттерне, так и в строке замены.
3+
Capturing groups may be accessed not only in the result, but in the replacement string, and in the pattern too.
64

75
[cut]
86

9-
## Группа в строке замены
7+
## Group in replacement: $n
108

11-
Ссылки в строке замены имеют вид `$n`, где `n` -- это номер скобочной группы.
9+
When we are using `replace` method, we can access n-th group in the replacement string using `$n`.
1210

13-
Вместо `$n` подставляется содержимое соответствующей скобки:
11+
For instance:
1412

1513
```js run
16-
var name = "Александр Пушкин";
14+
let name = "John Smith";
1715

18-
name = name.replace(/([а-яё]+) ([а-яё]+)/i, *!*"$2, $1"*/!*);
19-
alert( name ); // Пушкин, Александр
16+
name = name.replace(/(\w+) (\w+)/i, *!*"$2, $1"*/!*);
17+
alert( name ); // Smith, John
2018
```
2119

22-
В примере выше вместо `pattern:$2` подставляется второе найденное слово, а вместо `pattern:$1` -- первое.
20+
Here `pattern:$1` in the replacement string means "substitute the content of the first group here", and `pattern:$2` means "substitute the second group here".
2321

24-
## Группа в шаблоне
22+
Referencing a group in the replacement string allows us to reuse the existing text during the replacement.
2523

26-
Выше был пример использования содержимого групп в строке замены. Это удобно, когда нужно реорганизовать содержимое или создать новое с использованием старого.
24+
## Group in pattern: \n
2725

28-
Но к скобочной группе можно также обратиться в самом поисковом шаблоне, ссылкой вида `\номер`.
26+
A group can be referenced in the pattern using `\n`.
2927

30-
Чтобы было яснее, рассмотрим это на реальной задаче -- необходимо найти в тексте строку в кавычках. Причём кавычки могут быть одинарными `subject:'...'` или двойными `subject:"..."` -- и то и другое должно искаться корректно.
28+
To make things clear let's consider a task. We need to find a quoted string: either a single-quoted `subject:'...'` or a double-quoted `subject:"..."` -- both variants need to match.
3129

32-
Как такие строки искать?
30+
How to look for them?
3331

34-
Можно в регэкспе предусмотреть произвольные кавычки: `pattern:['"](.*?)['"]`. Такой регэксп найдёт строки вида `match:"..."`, `match:'...'`, но он даст неверный ответ в случае, если одна кавычка ненароком оказалась внутри другой, как например в строке `subject:"She's the one!"`:
32+
We can put two kinds of quotes in the pattern: `pattern:['"](.*?)['"]`. That finds strings like `match:"..."` and `match:'...'`, but it gives incorrect matches when one quote appears inside another one, like the string `subject:"She's the one!"`:
3533

3634
```js run
37-
var str = "He said: \"She's the one!\".";
35+
let str = "He said: \"She's the one!\".";
3836

39-
var reg = /['"](.*?)['"]/g;
37+
let reg = /['"](.*?)['"]/g;
4038

41-
// Результат не соответствует замыслу
39+
// The result is not what we expect
4240
alert( str.match(reg) ); // "She'
4341
```
4442

45-
Как видно, регэксп нашёл открывающую кавычку `match:"`, затем текст, вплоть до новой кавычки `match:'`, которая закрывает соответствие.
43+
As we can see, the pattern found an opening quote `match:"`, then the text is consumed lazily till the other quote `match:'`, that closes the match.
4644

47-
Для того, чтобы попросить регэксп искать закрывающую кавычку -- такую же, как открывающую, мы обернём её в скобочную группу и используем обратную ссылку на неё:
45+
To make sure that the pattern looks for the closing quote exactly the same as the opening one, let's make a group of it and use the backreference:
4846

4947
```js run
50-
var str = "He said: \"She's the one!\".";
48+
let str = "He said: \"She's the one!\".";
5149

52-
var reg = /(['"])(.*?)\1/g;
50+
let reg = /(['"])(.*?)\1/g;
5351

5452
alert( str.match(reg) ); // "She's the one!"
5553
```
5654

57-
Теперь работает верно! Движок регулярных выражений, найдя первое скобочное выражение -- кавычку `pattern:(['"])`, запоминает его и далее `pattern:\1` означает "найти то же самое, что в первой скобочной группе".
55+
Now everything's correct! The regular expression engine finds the first quote `pattern:(['"])` and remembers the content of `pattern:(...)`, that's the first capturing group.
5856

59-
Обратим внимание на два нюанса:
57+
Further in the pattern `pattern:\1` means "find the same text as in the first group".
6058

61-
- Чтобы использовать скобочную группу в строке замены -- нужно использовать ссылку вида `$1`, а в шаблоне -- обратный слэш: `\1`.
62-
- Чтобы в принципе иметь возможность обратиться к скобочной группе -- не важно откуда, она не должна быть исключена из запоминаемых при помощи `?:`. Скобочные группы вида `(?:...)` не участвуют в нумерации.
59+
Please note:
6360

61+
- To reference a group inside a replacement string -- we use `$1`, while in the pattern -- a backslash `\1`.
62+
- If we use `?:` in the group, then we can't reference it. Groups that are excluded from capturing `(?:...)` are not remembered by the engine.

10-regular-expressions-javascript/11-regexp-alternation/1-find-programming-language/solution.md renamed to 10-regular-expressions-javascript/11-regexp-alternation/01-find-programming-language/solution.md

File renamed without changes.

10-regular-expressions-javascript/11-regexp-alternation/1-find-programming-language/task.md renamed to 10-regular-expressions-javascript/11-regexp-alternation/01-find-programming-language/task.md

File renamed without changes.
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
2+
Opening tag is `pattern:\[(b|url|quote)\]`.
3+
4+
Then to find everything till the closing tag -- let's the pattern `pattern:[\s\S]*?` to match any character including the newline and then a backreference to the closing tag.
5+
6+
The full pattern: `pattern:\[(b|url|quote)\][\s\S]*?\[/\1\]`.
7+
8+
In action:
9+
10+
```js run
11+
let reg = /\[(b|url|quote)\][\s\S]*?\[\/\1\]/g;
12+
13+
let str = `
14+
[b]hello![/b]
15+
[quote]
16+
[url]http://google.com[/url]
17+
[/quote]
18+
`;
19+
20+
alert( str.match(reg) ); // [b]hello![/b],[quote][url]http://google.com[/url][/quote]
21+
```
22+
23+
Please note that we had to escape a slash for the closing tag `pattern:[/\1]`, because normally the slash closes the pattern.
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# Find bbtag pairs
2+
3+
A "bb-tag" looks like `[tag]...[/tag]`, where `tag` is one of: `b`, `url` or `quote`.
4+
5+
For instance:
6+
```
7+
[b]текст[/b]
8+
[url]http://google.com[/url]
9+
```
10+
11+
BB-tags can be nested. But a tag can't be nested into itself, for instance:
12+
13+
```
14+
Normal:
15+
[url] [b]http://google.com[/b] [/url]
16+
[quote] [b]text[/b] [/quote]
17+
18+
Impossible:
19+
[b][b]text[/b][/b]
20+
```
21+
22+
Tags can contain line breaks, that's normal:
23+
24+
```
25+
[quote]
26+
[b]text[/b]
27+
[/quote]
28+
```
29+
30+
Create a regexp to find all BB-tags with their contents.
31+
32+
For instance:
33+
34+
```js
35+
let reg = /your regexp/g;
36+
37+
let str = "..[url]http://google.com[/url]..";
38+
alert( str.match(reg) ); // [url]http://google.com[/url]
39+
```
40+
41+
If tags are nested, then we need the outer tag (if we want we can continue the search in its content):
42+
43+
```js
44+
let reg = /your regexp/g;
45+
46+
let str = "..[url][b]http://google.com[/b][/url]..";
47+
alert( str.match(reg) ); // [url][b]http://google.com[/b][/url]
48+
```

10-regular-expressions-javascript/11-regexp-alternation/2-match-quoted-string/solution.md renamed to 10-regular-expressions-javascript/11-regexp-alternation/03-match-quoted-string/solution.md

File renamed without changes.

10-regular-expressions-javascript/11-regexp-alternation/2-match-quoted-string/task.md renamed to 10-regular-expressions-javascript/11-regexp-alternation/03-match-quoted-string/task.md

File renamed without changes.

10-regular-expressions-javascript/11-regexp-alternation/3-match-exact-tag/solution.md renamed to 10-regular-expressions-javascript/11-regexp-alternation/04-match-exact-tag/solution.md

File renamed without changes.

0 commit comments

Comments
 (0)