Man regcomp (3): функции регулярных выражений POSIX. Man regcomp (3): функции регулярных выражений POSIX Освобождение буфера шаблона POSIX

  • 20.06.2020
Содержание

ereg

ereg -- парное значение регулярного выражения
Описание
int ereg (string pattern, string string, array );

Ищет парные значения string в регулярном выражении, указанном в pattern .

Если парные значения найдены для подстрок в круглых скобках pattern и функция вызывалась с третьим аргументом regs , то парные значения будут сохранены в элементах regs . $regs будет содержать подстроку, которая начинается с первой левой круглой скобки; $regs будет содержать подстроку, начинающуюся со второй скобки и т.д. $regs будет содержать копию string .

Поиск чуствителен к регистру.

Функция возвращает true, если парное значение для pattern было найдено в string, или false, если не было найдено парных значений или произошла ошибка.

Следующий код извлекает дату в ISO формате и выводит в формате DD.MM.YYYY:

Example 1. ereg() example

If (ereg("({4})-({1,2})-({1,2})", $date, $regs)) { echo "$regs.$regs.$regs"; } else { echo "Invalid date format: $date"; }

ereg_replace

ereg_replace -- заменяет регулярное выражение
Описание
string ereg_replace (string pattern, string replacement, string string);

Эта функция сканирует string на парные значения к pattern , затем заменяет найденный текст на replacement .

Если pattern содержит подстроки в круглых скобках, то replacement может содержать подстроки вида \\ цифра , которые будут заменены текстом, совпадающим с цифровой подстрокой в скобках; \\0 обработает все содержимое строки. Может быть использовано до 9 подстрок. Скобки могут быть сгруппированы, в этом случае они считаются по открывающим скобкам. Например, следующий код напечатет "This was a test" три раза:

Пример 1. ereg_replace()

$string = "This is a test"; echo ereg_replace(" is", " was", $string); echo ereg_replace("()is", "\\1was", $string); echo ereg_replace("(()is)", "\\2was", $string);

См. также , , и .

eregi

eregi -- нечувствительный к регистру поиск парных значений в регулярных выражениях
Описание
int eregi (string pattern, string string, array );

eregi_replace

eregi_replace -- замена регулярного выражения без учета регистра
Описание
string eregi_replace (string pattern, string replacement, string string);

split

split -- разбивает строку на массив по регулярному выражению
Описание
array split (string pattern, string string, int );

Возвращает массив строк, каждая из которых является подстрокой строки, образованные разбитием этой строки на части, отделенные друг от друга pattern . Если произойдет ошибка, функция вернет false.

Для получения первых 5 полей из строки в /etc/passwd:

Будет выдано .

Эта функция может быть использована организации нечувствительного к регистру сравнения в продуктах, которые поддерживают только чувстуительные к регистру выражения.

Format

#include int regcomp(regex_t *_restrict_ preg , const char *_restrict_ pattern , int cflags );

General description

Compiles the regular expression specified by pattern into an executable string of op-codes.

preg is a pointer to a compiled regular expression.

pattern is a pointer to a character string defining a source regular expression (described below).

cflags is a bit flag defining configurable attributes of compilation process: REG_EXTENDED Support extended regular expressions. REG_ICASE Ignore case in match. REG_NEWLINE Eliminate any special significance to the newline character. REG_NOSUB Report only success or fail in regexec(), that is, verify the syntax of a regular expression. If this flag is set, the regcomp() function sets re_nsub to the number of parenthesized sub-expressions found in pattern . Otherwise, a sub-expression results in an error.

The regcomp() function under z/OS XL C/C++ will use the definition of characters according to the current LC_SYNTAX category. The characters, [ , ] , { , } , | , ^ , and $ , have varying code points in different encoded character sets.

Regular expressions

The functions regcomp(), regerror(), regexec(), and regfree() use regular expressions in a similar way to the UNIX awk, ed, grep, and egrep commands.

The simplest form of regular expression is a string of characters with no special meaning. The following characters do have special meaning; they are used to form extended regular expressions: Symbol Description . The period symbol matches any one character except the terminal newline character. [character character ] The hyphen symbol, within square brackets, means “through”. It fills in the intervening characters according to the current collating sequence. For example, can be equivalent to or, with a different collating sequence, it can be equivalent to . [string ] A string within square brackets specifies any of the characters in string . Thus , if compared to other strings, would match any that contained a, b, or c.

No assumptions are made at compile time about the actual characters contained in the range.

{m } {m ,} {m ,u } Integer values enclosed in {} indicate the number of times to apply the preceding regular expression. m is the minimum number, and u is the maximum number. u must not be greater than RE_DUP_MAX (see limits.h).

If you specify only m , it indicates the exact number of times to apply the regular expression. {m ,} is equivalent to {m,u }. They both match m or more occurrences of the expression.

* The asterisk symbol indicates 0 or more of any characters. For example, [ a*e ] is equivalent to any of the following: 99ae9, aaaaae, a999e99. $ The dollar symbol matches the end of the string. (Use \n to match a newline character.) character + The plus symbol specifies one or more occurrences of a character. Thus, smith+ern is equivalent to, for example, smithhhern . [^string ] The caret symbol, when inside square brackets, negates the characters within the square brackets. Thus [^abc] , if compared to other strings, would fail to match any that contains even one a, b, or c. (expression )$n Stores the value matched by the enclosed regular expression in the (n +1) th ret parameter. Ten enclosed regular expressions are allowed. Assignments are made unconditionally. (expression ) Groups a sub-expression allowing an operator, such as *, +, or .], to work on the sub-expression enclosed in parentheses. For example, (a*(cb+)*)$0 .

Note:

  1. Do not use multibyte characters.
  2. You can use the ] (right square bracket) alone within a pair of square brackets, but only if it immediately follows either the opening left square bracket or if it immediately follows [^. For example: –] matches the ] and – characters.
  3. All the preceding symbols are special . You precede them with \ to use the symbol itself. For example, a\.e is equivalent to a.e .
  4. You can use the – (hyphen) by itself, but only if it is the first or last character in the expression. For example, the expression --0] matches either the ] or else the characters – through 0. Otherwise, use \–.

Returned value

If successful, regcomp() returns 0.

If unsuccessful, regcomp() returns nonzero, and the content of preg is undefined.

Example

CELEBR07 ⁄* CELEBR07 This example compiles an extended regular expression. *⁄ #include #include #include #include main() { regex_t preg; char *string = "a simple string"; char *pattern = ".*(simple).*"; int rc; if ((rc = regcomp(&preg, pattern, REG_EXTENDED)) != 0) { printf("regcomp() failed, returning nonzero (%d)", rc); exit(1); } }

> int regcomp(regex_t * preg , const char * regex , int cflags ); int regexec(const regex_t * preg , const char * string , size_t nmatch , regmatch_t pmatch , int eflags ); size_t regerror(int errcode , const regex_t * preg , char * errbuf , size_t errbuf_size ); void regfree(regex_t * preg );

ОПИСАНИЕ

Компилирование регулярных выражений POSIX

Функция regcomp () используется для компиляции регулярного выражения вформат, который подходит для последующих поисков с помощью regexec ().

regcomp () передаётся указатель на область хранения буферного шаблонаpreg , указатель на заканчивающуюся null строку regex и флагиcflags , используемые для определения типа компиляции.

Все поиски регулярных выражений должны выполняться с помощьюскомпилированного буферного шаблона, поэтому regexec () должна всегдавызываться с адресом буферного шаблона, инициализированного функциейregcomp ().

Значение cflags может состоять из поразрядного or нуля или несколькихследующих значений: REG_EXTENDED Использовать синтаксис расширенных регулярных выражений POSIX во времяинтерпретации regex . Если не включён этот флаг, то используется синтаксиспростых регулярных выражений POSIX. REG_ICASE Не учитывать регистр. Последующие поиски regexec () с использованиемданного буферного шаблона не будут зависеть от регистра. REG_NOSUB Не сообщать положение совпадений. Параметры nmatch и pmatch дляregexec () игнорируются, если данный буферный шаблон был скомпилирован сэтим включённым флагом. REG_NEWLINE Операторы совпадения с любым символом не совпадают с символом новой строки. Список несовпадающих символов ([^...] ) без символа новой строки несовпадает с новой строкой. Оператор сравнения по началу строки (^ ) совпадает с пустой строкой сразупосле новой строки независимо от того, что eflags , флаги выполненияregexec (), содержат REG_NOTBOL . Оператор сравнения по концу строки ($) совпадает с пустой строкой до символаначала строки независимо от того, что eflags содержит REG_NOTEOL .

Сравнение с регулярным выражением POSIX

Функция regexec () используется для сравнения строки, завершающейся null,с предварительно обработанным буферным шаблоном preg . Аргументы nmatch и pmatch используются для предоставления информации о местонахождениилюбых совпадений. Значение eflags может быть поразрядным ИЛИ одногоили обоих значений REG_NOTBOL и REG_NOTEOL . Данные значения определяютповедение процесса сравнения так, как описано ниже. REG_NOTBOL Оператор сравнения по началу строки всегда завершается с ошибкой (носмотрите описанный выше флаг компиляции REG_NEWLINE ). Этот флаг можетиспользоваться, когда в regexec () передаются отдельные части строки, иначало такой строки в данном случае не должно интерпретироваться как началоновой строки. REG_NOTEOL Оператор сравнения по концу строки всегда завершается с ошибкой (но смотритеописанный выше флаг компиляции REG_NEWLINE ).

Байтовые смещения

Если REG_NOSUB не установлен при компиляции буферного шаблона, товозможно получать информацию о положении совпадений. Значение pmatch должно быть определено так, чтобы иметь, по крайней мере, nmatch элементов. Они заполняются regexec () адресами внутристрочныхсовпадений. Смещения подвыражения, начинающегося с i -й открытой скобки,сохраняется в pmatch[i] . Адрес совпадения всего регулярного выражениясохраняется в pmatch (заметим, что чтобы вернуть смещения совпаденийN подвыражений, значение nmatch должно быть не менее N+1 ). Любыенеиспользованные элементы структуры будут содержать значение -1.

Структура regmatch_t , являющаяся типом pmatch , определена в :

typedef struct {
regoff_t rm_so;
regoff_t rm_eo;} regmatch_t;

Каждый элемент rm_so , не равный -1, показывает начальное смещениеследующего совпадения наибольшей подстроки внутри заданнойстроки. Относительный элемент rm_eo указывает на смещение концасовпадения, которое является первым символом после совпавшего текста.

Сообщение об ошибках POSIX

Функция regerror используется для преобразования кодов ошибок, которыемогут быть получены от regcomp () и regexec (), в строки сообщений обошибках.

В regerror передаются: код ошибки errcode , буферный шаблон preg ,указатель на символьный буфер строки errbuf и размер буфера строкиerrbuf_size . Функция возвращает размер errbuf , который требуется длясохранения сообщения об ошибке в виде строки, оканчивающейся null. Если иerrbuf , и errbuf_size не равны нулю, то errbuf заполняется первымиerrbuf_size - 1 символами сообщения об ошибке и завершается байтом null(aq\0aq).

Освобождение буфера шаблона POSIX

Функция regfree () освобождает память, отведённую буферному шаблонуpreg во время процесса компиляции с помощью regcomp ().

ВОЗВРАЩАЕМОЕ ЗНАЧЕНИЕ

Функция regcomp () возвращает ноль при успешной компиляции или в противномслучае код ошибки.

Функция regexec () возвращает ноль при совпадении или REG_NOMATCH , еслисовпадений не было.

ОШИБКИ

Функция regcomp () может возвращать следующие ошибки: REG_BADBR Неправильное использование оператора обратных ссылок. REG_BADPAT Неправильное использование операторов шаблона, таких, как операторы группыили списка. REG_BADRPT Неправильное использование операторов повторения, например, использование«*» в качестве первого символа. REG_EBRACE Непарные скобки в операторах интервала. REG_EBRACK Непарные квадратные скобки в операторах списка. REG_ECOLLATE Неправильный элемент сортировки. REG_ECTYPE Неизвестное имя класса символов. REG_EEND Потенциальная ошибка. Не определена в POSIX.2. REG_EESCAPE Конечная обратная косая черта. REG_EPAREN Непарные круглые скобки в операторах группировки. REG_ERANGE Неправильное использование оператора области: например, конец областипоявляется прежде её начала. REG_ESIZE Скомпилированное регулярное выражение требует буферный шаблон размером,большим 64 Кб. Это не определено в POSIX.2. REG_ESPACE Для процедур регулярных выражений закончилась память. REG_ESUBREG Неправильная обратная ссылка на подвыражение.

> int regcomp(regex_t * preg , const char * regex , int cflags ); int regexec(const regex_t * preg , const char * string , size_t nmatch , regmatch_t pmatch , int eflags ); size_t regerror(int errcode , const regex_t * preg , char * errbuf , size_t errbuf_size ); void regfree(regex_t * preg );

Description

POSIX regex compiling regcomp () is used to compile a regular expression into a form that is suitable for subsequent regexec () searches.

regcomp () is supplied with preg , a pointer to a pattern buffer storage area; regex , a pointer to the null-terminated string and cflags , flags used to determine the type of compilation.

All regular expression searching must be done via a compiled pattern buffer, thus regexec () must always be supplied with the address of a regcomp () initialized pattern buffer.

cflags may be the bitwise-or of one or more of the following: REG_EXTENDED Use POSIX Extended Regular Expression syntax when interpreting regex . If not set, POSIX Basic Regular Expression syntax is used. REG_ICASE Do not differentiate case. Subsequent regexec () searches using this pattern buffer will be case insensitive. REG_NOSUB Do not report position of matches. The nmatch and pmatch arguments to regexec () are ignored if the pattern buffer supplied was compiled with this flag set. REG_NEWLINE Match-any-character operators don"t match a newline.

A nonmatching list ([^...] ) not containing a newline does not match a newline.

Match-beginning-of-line operator (^ ) matches the empty string immediately after a newline, regardless of whether eflags , the execution flags of regexec (), contains REG_NOTBOL .

Match-end-of-line operator ($ ) matches the empty string immediately before a newline, regardless of whether eflags contains REG_NOTEOL .

POSIX regex matching regexec () is used to match a null-terminated string against the precompiled pattern buffer, preg . nmatch and pmatch are used to provide information regarding the location of any matches. eflags may be the bitwise-or of one or both of REG_NOTBOL and REG_NOTEOL which cause changes in matching behavior described below. REG_NOTBOL The match-beginning-of-line operator always fails to match (but see the compilation flag REG_NEWLINE above) This flag may be used when different portions of a string are passed to regexec () and the beginning of the string should not be interpreted as the beginning of the line. REG_NOTEOL The match-end-of-line operator always fails to match (but see the compilation flag REG_NEWLINE above)

Byte offsets Unless REG_NOSUB was set for the compilation of the pattern buffer, it is possible to obtain match addressing information. pmatch must be dimensioned to have at least nmatch elements. These are filled in by regexec () with substring match addresses. The offsets of the subexpression starting at the i th open parenthesis are stored in pmatch[i] . The entire regular expression"s match addresses are stored in pmatch . (Note that to return the offsets of N subexpression matches, nmatch must be at least N+1 .) Any unused structure elements will contain the value -1.

The regmatch_t structure which is the type of pmatch is defined in .

Typedef struct { regoff_t rm_so; regoff_t rm_eo; } regmatch_t; Each rm_so element that is not -1 indicates the start offset of the next largest substring match within the string. The relative rm_eo element indicates the end offset of the match, which is the offset of the first character after the matching text.

POSIX error reporting regerror () is used to turn the error codes that can be returned by both regcomp () and regexec () into error message strings.

regerror () is passed the error code, errcode , the pattern buffer, preg , a pointer to a character string buffer, errbuf , and the size of the string buffer, errbuf_size . It returns the size of the errbuf required to contain the null-terminated error message string. If both errbuf and errbuf_size are nonzero, errbuf is filled in with the first errbuf_size - 1 characters of the error message and a terminating null byte ("\0").

POSIX pattern buffer freeing Supplying regfree () with a precompiled pattern buffer, preg will free the memory allocated to the pattern buffer by the compiling process, regcomp ().

Return Value

regcomp () returns zero for a successful compilation or an error code for failure.

regexec () returns zero for a successful match or REG_NOMATCH for failure.

Errors

The following errors can be returned by regcomp (): REG_BADBR Invalid use of back reference operator. REG_BADPAT Invalid use of pattern operators such as group or list. REG_BADRPT Invalid use of repetition operators such as using "*" as the first character. REG_EBRACE Un-matched brace interval operators. REG_EBRACK Un-matched bracket list operators. REG_ECOLLATE Invalid collating element. REG_ECTYPE Unknown character class name. REG_EEND Nonspecific error. This is not defined by POSIX.2. REG_EESCAPE Trailing backslash. REG_EPAREN Un-matched parenthesis group operators. REG_ERANGE Invalid use of the range operator, e.g., the ending point of the range occurs prior to the starting point. REG_ESIZE Compiled regular expression requires a pattern buffer larger than 64Kb. This is not defined by POSIX.2. REG_ESPACE The regex routines ran out of memory. REG_ESUBREG Invalid back reference to a subexpression.