Skip to content

Commit 5514fae

Browse files
authored
Update article.md
1 parent b189e22 commit 5514fae

1 file changed

Lines changed: 28 additions & 28 deletions

File tree

9-regular-expressions/09-regexp-groups/article.md

Lines changed: 28 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -113,39 +113,39 @@ alert(result); // <span class="my">, span class="my", span, class="my"
113113

114114
**Даже если скобочная группа необязательна и не входит в совпадение, соответствующий элемент массива `result` существует (и равен `undefined`).**
115115

116-
For instance, let's consider the regexp `pattern:a(z)?(c)?`. It looks for `"a"` optionally followed by `"z"` optionally followed by `"c"`.
116+
Например, рассмотрим регэксп `pattern:a(z)?(c)?`. Он ищет `"a"`, за которой не обязательно идёт буква `"z"`, за которой не обязательно идёт буква `"c"`.
117117

118-
If we run it on the string with a single letter `subject:a`, then the result is:
118+
Если запустить его на строку из одной буквы `subject:a`, то результат будет таков:
119119

120120
```js run
121121
let match = 'a'.match(/a(z)?(c)?/);
122122

123123
alert( match.length ); // 3
124-
alert( match[0] ); // a (whole match)
124+
alert( match[0] ); // a (всё совпадение)
125125
alert( match[1] ); // undefined
126126
alert( match[2] ); // undefined
127127
```
128128

129-
The array has the length of `3`, but all groups are empty.
129+
Массив имеет длинну `3`, но все скобочные группы пустые.
130130

131-
And here's a more complex match for the string `subject:ack`:
131+
А теперь более сложная ситуация для строки `subject:ack`:
132132

133133
```js run
134134
let match = 'ack'.match(/a(z)?(c)?/)
135135

136136
alert( match.length ); // 3
137-
alert( match[0] ); // ac (whole match)
138-
alert( match[1] ); // undefined, because there's nothing for (z)?
137+
alert( match[0] ); // ac (всё совпадение)
138+
alert( match[1] ); // undefined, потому что для (z)? ничего нет
139139
alert( match[2] ); // c
140140
```
141141

142-
The array length is permanent: `3`. But there's nothing for the group `pattern:(z)?`, so the result is `["ac", undefined, "c"]`.
142+
Длинна массива всегда: `3`. Для группы `pattern:(z)?` ничего нет, поэтому результат `["ac", undefined, "c"]`.
143143

144-
## Named groups
144+
## Именованные группы
145145

146-
Remembering groups by their numbers is hard. For simple patterns it's doable, but for more complex ones we can give names to parentheses.
146+
Запоминать группы по числам сложно. Для простых шаблонов это допустимо, но в более сложных случаях мы можем дать имена скобкам.
147147

148-
That's done by putting `pattern:?<name>` immediately after the opening paren, like this:
148+
Это делается добавлением `pattern:?<name>` непосредственно после открытия скобки. Например:
149149

150150
```js run
151151
*!*
@@ -160,11 +160,11 @@ alert(groups.month); // 04
160160
alert(groups.day); // 30
161161
```
162162

163-
As you can see, the groups reside in the `.groups` property of the match.
163+
Как вы можете видеть, группы располагаются в свойстве `.groups` совпадения.
164164

165-
We can also use them in replacements, as `pattern:$<name>` (like `$1..9`, but name instead of a digit).
165+
МЫ также можем использовать их для замены, как `pattern:$<name>` (как в случае с `$1..9`, но использовать имя вместо цифры).
166166

167-
For instance, let's rearrange the date into `day.month.year`:
167+
Например, давайте переделаем информацию о дате `day.month.year`:
168168

169169
```js run
170170
let dateRegexp = /(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})/;
@@ -176,7 +176,7 @@ let rearranged = str.replace(dateRegexp, '$<day>.$<month>.$<year>');
176176
alert(rearranged); // 30.04.2019
177177
```
178178

179-
If we use a function, then named `groups` object is always the last argument:
179+
Если используем функцию, тогда именованный объект `groups` всегда является последним аргументом:
180180

181181
```js run
182182
let dateRegexp = /(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})/;
@@ -191,9 +191,9 @@ let rearranged = str.replace(dateRegexp,
191191
alert(rearranged); // 30.04.2019
192192
```
193193

194-
Usually, when we intend to use named groups, we don't need positional arguments of the function. For the majority of real-life cases we only need `str` and `groups`.
194+
Обычно, когдам мы планируем использовать именованные группы, то нам не нужны позиционированные аргументы функции. Для большинства реальных случаев нам нужны только `str` и` groups`.
195195

196-
So we can write it a little bit shorter:
196+
Таким образом, мы можем написать это немного короче:
197197

198198
```js
199199
let rearranged = str.replace(dateRegexp, (str, ...args) => {
@@ -206,20 +206,20 @@ let rearranged = str.replace(dateRegexp, (str, ...args) => {
206206
```
207207

208208

209-
## Non-capturing groups with ?:
209+
## Исключение из запоминания через ?:
210210

211-
Sometimes we need parentheses to correctly apply a quantifier, but we don't want the contents in results.
211+
Бывает так, что скобки нужны, чтобы квантификатор правильно применился, но мы не хотим содержимое в результате.
212212

213-
A group may be excluded by adding `pattern:?:` in the beginning.
213+
Скобочную группу можно исключить из запоминаемых и нумеруемых, добавив в её начало `pattern:?:`.
214214

215-
For instance, if we want to find `pattern:(go)+`, but don't want to remember the contents (`go`) in a separate array item, we can write: `pattern:(?:go)+`.
215+
Например, если мы хотим найти `pattern:(go)+`, но не хотим запоминать содержимое (`go`) в отдельный элемент массива, то можем написать так: `pattern:(?:go)+`.
216216

217-
In the example below we only get the name "John" as a separate member of the `results` array:
217+
В примере ниже мы получаем только имя "John", как отдельный член массива `results`:
218218

219219
```js run
220220
let str = "Gogo John!";
221221
*!*
222-
// exclude Gogo from capturing
222+
// исключает Gogo из запоминания
223223
let reg = /(?:go)+ (\w+)/i;
224224
*/!*
225225

@@ -229,9 +229,9 @@ alert( result.length ); // 2
229229
alert( result[1] ); // John
230230
```
231231

232-
## Summary
232+
## Итого
233233

234-
- Parentheses can be:
235-
- capturing `(...)`, ordered left-to-right, accessible by number.
236-
- named capturing `(?<name>...)`, accessible by name.
237-
- non-capturing `(?:...)`, used only to apply quantifier to the whole groups.
234+
- Скобки могут:
235+
- запоминать `(...)`, нумеровать слева направо, давать доступ по номеру.
236+
- именовать группы `(?<name>...)`, давать доступ по имени.
237+
- исключать из запоминания `(?:...)`, использоваться только для применения квантификатора ко всем группам.

0 commit comments

Comments
 (0)