.\" -*- coding: UTF-8 -*- .ie t .ds dg \(dg .el .ds dg (!) '\" t .\" From Henry Spencer's regex package (as found in the apache .\" distribution). The package carries the following copyright: .\" .\" Copyright 1992, 1993, 1994 Henry Spencer. All rights reserved. .\" %%%LICENSE_START(MISC) .\" This software is not subject to any license of the American Telephone .\" and Telegraph Company or of the Regents of the University of California. .\" .\" Permission is granted to anyone to use this software for any purpose .\" on any computer system, and to alter it and redistribute it, subject .\" to the following restrictions: .\" .\" 1. The author is not responsible for the consequences of use of this .\" software, no matter how awful, even if they arise from flaws in it. .\" .\" 2. The origin of this software must not be misrepresented, either by .\" explicit claim or by omission. Since few users ever read sources, .\" credits must appear in the documentation. .\" .\" 3. Altered versions must be plainly marked as such, and must not be .\" misrepresented as being the original software. Since few users .\" ever read sources, credits must appear in the documentation. .\" .\" 4. This notice may not be removed or altered. .\" %%%LICENSE_END .\" .\" In order to comply with `credits must appear in the documentation' .\" I added an AUTHOR paragraph below - aeb. .\" .\" In the default nroff environment there is no dagger \(dg. .\" .\" 2005-05-11 Removed discussion of `[[:<:]]' and `[[:>:]]', which .\" appear not to be in the glibc implementation of regcomp .\" .\"******************************************************************* .\" .\" This file was generated with po4a. Translate the source file. .\" .\"******************************************************************* .TH regex 7 "15 декабря 2022 г." "Linux man\-pages 6.02" .SH ИМЯ regex \- регулярные выражения POSIX.2 .SH ОПИСАНИЕ Регулярные выражения (РВ) стандарта POSIX.2 могут быть двух видов: новые РВ (по сути, использующиеся в \fIegrep\fP; в POSIX.2 их называют ещё «расширенными» РВ) и устаревшие РВ (по сути, использующиеся в \fBed\fP(1); в POSIX.2 их называют ещё «основными» РВ). Устаревшие РВ существуют, в основном, для совместимости с некоторыми старыми программами (они будут подробнее рассмотрены в конце этого документа). В POSIX.2 не разъяснены некоторые вопросы синтаксиса РВ; знаком \*(dg отмечаются описания, которые могут быть не полностью совместимы с другими реализациями POSIX.2. .PP Новое РВ — одна\*(dg или более непустых\*(dg \fIветвей\fP, разделённых \(aq|\(aq. Соответствием считается, если есть совпадение для любой из её ветвей. .PP Ветвь состоит из одной\*(dg или более \fIчастей\fP. Ветвь сначала ведёт поиск соответствий с первой, затем с второй (и т. п.) её частями. .PP Часть — это \fIатом\fP, за которым может следовать одиночный\*(dg символ \(aq*\(aq, \(aq+\(aq, \(aq?\(aq или \fIинтервал\fP. Если за атомом следует символ \(aq*\(aq, это означает, что совпадающая с атомом последовательность может встречаться 0 или более раз. Если за атомом следует символ \(aq+\(aq, это означает, что совпадающая с атомом последовательность может встречаться 1 или более раз. Если за атомом следует символ \(aq?\(aq, это означает, что совпадающая с атомом последовательность может встречаться 0 или 1 раз. .PP \fIИнтервал\fP — это символ \(aq{\(aq, после которого стоит беззнаковое целое десятичное число, за которым может следовать символ \(aq,\(aq, далее, возможно, находится ещё одно беззнаковое целое десятичное число, и в конце интервала обязательно стоит символ \(aq}\(aq. Числа должны находиться в промежутке от 0 до \fBRE_DUP_MAX\fP (255\*(dg) включительно, а если указано два числа, то первое не должно превышать второе. Атом с интервалом, в котором есть одно число \fIi\fP и нет запятой, соответствует последовательности, повторяющейся точно \fIi\fP раз. Атом с интервалом, содержащим число \fIi\fP и запятую, соответствует последовательности, повторяющейся \fIi\fP и более раз. Атом с интервалом, содержащим два числа \fIi\fP и \fIj\fP, соответствует последовательности, повторяющейся от \fIi\fP до \fIj\fP раз включительно. .PP An atom is a regular expression enclosed in "\fI()\fP" (matching a match for the regular expression), an empty set of "\fI()\fP" (matching the null string)\*(dg, a \fIbracket expression\fP (see below), \(aq.\(aq (matching any single character), \(aq\(ha\(aq (matching the null string at the beginning of a line), \(aq$\(aq (matching the null string at the end of a line), a \(aq\e\(aq followed by one of the characters "\fI\(ha.[$()|*+?{\e\fP" (matching that character taken as an ordinary character), a \(aq\e\(aq followed by any other character\*(dg (matching that character taken as an ordinary character, as if the \(aq\e\(aq had not been present\*(dg), or a single character with no other significance (matching that character). A \(aq{\(aq followed by a character other than a digit is an ordinary character, not the beginning of a bound\*(dg. It is illegal to end an RE with \(aq\e\(aq. .PP A \fIbracket expression\fP is a list of characters enclosed in "\fI[]\fP". It normally matches any single character from the list (but see below). If the list begins with \(aq\(ha\(aq, it matches any single character (but see below) \fInot\fP from the rest of the list. If two characters in the list are separated by \(aq\-\(aq, this is shorthand for the full \fIrange\fP of characters between those two (inclusive) in the collating sequence, for example, "\fI[0\-9]\fP" in ASCII matches any decimal digit. It is illegal\*(dg for two ranges to share an endpoint, for example, "\fIa\-c\-e\fP". Ranges are very collating\-sequence\-dependent, and portable programs should avoid relying on them. .PP To include a literal \(aq]\(aq in the list, make it the first character (following a possible \(aq\(ha\(aq). To include a literal \(aq\-\(aq, make it the first or last character, or the second endpoint of a range. To use a literal \(aq\-\(aq as the first endpoint of a range, enclose it in "\fI[.\fP" and "\fI.]\fP" to make it a collating element (see below). With the exception of these and some combinations using \(aq[\(aq (see next paragraphs), all other special characters, including \(aq\e\(aq, lose their special significance within a bracket expression. .PP Если внутри квадратных скобок объединяющий элемент (одиночный символ, многосимвольная последовательность, которая действует как одиночный символ или имя объединяющей последовательности) заключен в «\fI[.\fP» и «\fI.]\fP», то он обозначает последовательность символов как один объединяющий элемент. Последовательность выражается одиночным элементом списка внутри квадратных скобок. Таким образом, выражение в скобках, содержащее многосимвольный объединяющий элемент, может соответствовать более чем одному символу; например, если последовательность содержит объединяющий элемент «ch», то РВ «\fI[[.ch.]]*c\fP» соответствует первым пяти символам «chchcc». .PP Within a bracket expression, a collating element enclosed in "\fI[=\fP" and "\fI=]\fP" is an equivalence class, standing for the sequences of characters of all collating elements equivalent to that one, including itself. (If there are no other equivalent collating elements, the treatment is as if the enclosing delimiters were "\fI[.\fP" and "\fI.]\fP".) For example, if o and \(^o are the members of an equivalence class, then "\fI[[=o=]]\fP", "\fI[[=\(^o=]]\fP", and "\fI[o\(^o]\fP" are all synonymous. An equivalence class may not\*(dg be an endpoint of a range. .PP В выражении в квадратных скобках, имя \fIсимвольного класса\fP, заключенное в «\fI[:\fP» и «\fI:]\fP», соответствует списку всех символов, принадлежащих этому классу. Существуют стандартные символьные классы: .PP .RS .TS l l l. alnum digit punct alpha graph space blank lower upper cntrl print xdigit .TE .RE .PP .\" As per http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=295666 .\" The following does not seem to apply in the glibc implementation .\" .PP .\" There are two special cases\*(dg of bracket expressions: .\" the bracket expressions "\fI[[:<:]]\fP" and "\fI[[:>:]]\fP" match .\" the null string at the beginning and end of a word respectively. .\" A word is defined as a sequence of .\" word characters .\" which is neither preceded nor followed by .\" word characters. .\" A word character is an .\" .I alnum .\" character (as defined by .\" .BR wctype (3)) .\" or an underscore. .\" This is an extension, .\" compatible with but not specified by POSIX.2, .\" and should be used with .\" caution in software intended to be portable to other systems. Эти символьные классы определены в \fBwctype\fP(3). В локали могут быть определены свои классы. Символьный класс не может использоваться в качестве границы диапазона. .PP В случае, если РВ совпадает более чем с одной подстрокой заданной строки, то оно считается совпадающим с первой подстрокой строки. Если РВ совпадает более чем с одной подстрокой начинающейся в этой точке, то оно совпадет с самой длинной подстрокой. Подвыражения также соответствуют самой длинной совпадающей подстроке, полное соответствие должно быть наиболее длинным, и подвыражения, стоящие в РВ первыми, имеют приоритет над остальными, находящимися далее. Заметим, что высокоуровневые подвыражения имеют приоритет над низкоуровневыми компонентами подвыражений. .PP Длина совпадений измеряется в символах, а не в объединяющих элементах. Строка null считается длиннее чем не имеющая совпадений. Например, «\fIbb*\fP» совпадает с тремя средними символами «abbbc», «\fI(wee|week)(knights|nights)\fP» совпадает со всеми десятью символами «weeknights», а когда «\fI(.*).*\fP» сравнивается с «abc», подвыражение в скобках совпадает со всеми тремя символами; при сравнении «\fI(a*)*\fP» с «bc» получается, что РВ и подвыражение в скобках соответствуют строке null. .PP If case\-independent matching is specified, the effect is much as if all case distinctions had vanished from the alphabet. When an alphabetic that exists in multiple cases appears as an ordinary character outside a bracket expression, it is effectively transformed into a bracket expression containing both cases, for example, \(aqx\(aq becomes "\fI[xX]\fP". When it appears inside a bracket expression, all case counterparts of it are added to the bracket expression, so that, for example, "\fI[x]\fP" becomes "\fI[xX]\fP" and "\fI[\(hax]\fP" becomes "\fI[\(haxX]\fP". .PP Конкретного ограничения длины РВ\*(dg не существует. Однако, в переносимых программах не следует использовать РВ более 256 байтов, так как реализация может не принимать таких РВ, но оставаться соответствующей POSIX. .PP Obsolete ("basic") regular expressions differ in several respects. \(aq|\(aq, \(aq+\(aq, and \(aq?\(aq are ordinary characters and there is no equivalent for their functionality. The delimiters for bounds are "\fI\e{\fP" and "\fI\e}\fP", with \(aq{\(aq and \(aq}\(aq by themselves ordinary characters. The parentheses for nested subexpressions are "\fI\e(\fP" and "\fI\e)\fP", with \(aq(\(aq and \(aq)\(aq by themselves ordinary characters. \(aq\(ha\(aq is an ordinary character except at the beginning of the RE or\*(dg the beginning of a parenthesized subexpression, \(aq$\(aq is an ordinary character except at the end of the RE or\*(dg the end of a parenthesized subexpression, and \(aq*\(aq is an ordinary character if it appears at the beginning of the RE or the beginning of a parenthesized subexpression (after a possible leading \(aq\(ha\(aq). .PP Кроме этого, существует ещё один тип атома — \fIобратная ссылка\fP: \(aq\e\(aq с последующей за ней ненулевой десятичной цифрой \fId\fP соответствует той самой последовательности, что и \fId\fP\-е подвыражение в скобках (нумерация подвыражений считается по их открывающим круглым скобкам, слева направо). Пример: «\fI\e([bc]\e)\e1\fP» соответствует «bb» или «cc», но не «bc». .SH ДЕФЕКТЫ Наличие двух видов РВ — вынужденная мера. .PP В имеющейся на данный момент документации POSIX.2 указано, что символ \(aq)\(aq при отсутствии \(aq(\(aq; считается обычным; это непреднамеренная опечатка, которая будет исправлена. Не полагайтесь на это. .PP Обратные ссылки — также вынужденная мера, вызывают серьёзные проблемы эффективности в реализациях. Также они не имеют подробного определения (например, «\fIa\e(\e(b\e)*\e2\e)*d\fP» соответствует «abbbd»?). .PP .\" As per http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=295666 .\" The following does not seem to apply in the glibc implementation .\" .PP .\" The syntax for word boundaries is incredibly ugly. Определение в POSIX.2 совпадения при отключении учёта регистра тоже очень туманное. Определение типа «один регистр замещает все остальные», по мнению некоторых специалистов, не является правильным. .SH АВТОРЫ .\" Sigh... The page license means we must have the author's name .\" in the formatted output. Эта страница взята из пакета regex, написанного Генри Спенсером (Henry Spencer). .SH "СМ. ТАКЖЕ" \fBgrep\fP(1), \fBregex\fP(3) .PP POSIX.2, раздел 2.8 (запись регулярных выражений). .PP .SH ПЕРЕВОД Русский перевод этой страницы руководства был сделан aereiae , Azamat Hackimov , Dmitriy S. Seregin , Katrin Kutepova , Lockal , Yuri Kozlov , Баринов Владимир и Иван Павлов . .PP Этот перевод является бесплатной документацией; прочитайте .UR https://www.gnu.org/licenses/gpl-3.0.html Стандартную общественную лицензию GNU версии 3 .UE или более позднюю, чтобы узнать об условиях авторского права. Мы не несем НИКАКОЙ ОТВЕТСТВЕННОСТИ. .PP Если вы обнаружите ошибки в переводе этой страницы руководства, пожалуйста, отправьте электронное письмо на .MT man-pages-ru-talks@lists.sourceforge.net .ME .