Scroll to navigation

regex(3) Library Functions Manual regex(3)

NOMBRE

regcomp, regexec, regerror, regfree - funciones para expresiones regulares POSIX

BIBLIOTECA

Biblioteca Estándar C (libc, -lc)

SINOPSIS

#include <regex.h>
int regcomp(regex_t *restrict preg, const char *restrict regex,
            int cflags);
int regexec(const regex_t *restrict preg, const char *restrict string,
            size_t nmatch, regmatch_t pmatch[restrict .nmatch],
            int eflags);
size_t regerror(int errcode, const regex_t *restrict preg,
            char errbuf[restrict .errbuf_size], size_t errbuf_size);
void regfree(regex_t *preg);

DESCRIPCIÓN

Compilación de expresiones regulares POSIX

regcomp() se utiliza para compilar una expresión regular en un formato apropiado para ser usado por regexec() en búsquedas posteriores.

A regcomp() se le pasan como parámetros preg, un puntero a un área de almacenamiento temporal de patrones, regex, un puntero a una cadena terminada en un carácter nulo y cflags, banderas utilizadas para determinar el tipo de compilación.

Toda búsqueda con expresiones regulares se debe realizar mediante un buffer de patrones compilados, por tanto, a regexec() siempre se le debe proporcionar la dirección de un buffer de patrones inicializado mediante regcomp().

cflags is the bitwise-or of zero or more of the following:

Utilizar el tipo de sintaxis 'Expresión Regular Extendida POSIX' cuando se interprete regex. Si no se activa esta opción, se utiliza el tipo de sintaxis 'Expresión Regular Básica POSIX'.
No distinguir entre mayúsculas y minúsculas. Las siguientes búsquedas regexec() que usen este buffer de patrones no distinguirán entre mayúsculas y minúsculas.
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.
Los operadores "coincidir con cualquier carácter" no coinciden con un carácter "nueva línea".
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.
Un operador "coincidir al final de línea" ($) coincide con la cadena vacía inmediatamente anterior a un carácter "nueva línea", sin tener en cuenta si eflags contiene REG_NOTEOL o no.

Coincidencias en las expresiones regulares POSIX

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 is the bitwise-or of zero or more of the following flags:

El operador "coincidir al principio de línea" siempre falla en las coincidencias (pero vea la opción de compilación REG_NEWLINE más arriba). Esta bandera se puede utilizar cuando se pasan diferentes porciones de una cadena a regexec() y el comienzo de la cadena no se debe interpretar como el principio de una línea.
El operador "coincidir al final de línea" siempre falla en la coincidencias (pero vea la opción de compilación REG_NEWLINE más arriba).
Use pmatch[0] on the input string, starting at byte pmatch[0].rm_so and ending before byte pmatch[0].rm_eo. This allows matching embedded NUL bytes and avoids a strlen(3) on large strings. It does not use nmatch on input, and does not change REG_NOTBOL or REG_NEWLINE processing. This flag is a BSD extension, not present in POSIX.

Desplazamientos de bytes

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 ith open parenthesis are stored in pmatch[i]. The entire regular expression's match addresses are stored in pmatch[0]. (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.

La estructura regmatch_t, que es el tipo de pmatch, se define en <regex.h>.


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.

Informes de error POSIX

regerror() se utiliza para convertir los códigos de error que pueden devolver tanto regcomp() como regexec() en cadenas de mensaje de error.

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').

Liberación de buffers de patrones POSIX

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

VALOR DEVUELTO

regcomp() devuelve cero si la compilación tiene éxito y un código de error si falla.

regexec() devuelve cero si hay coincidencia y REG_NOMATCH en caso de fallo.

ERRORES

regcomp() puede devolver los siguientes errores:

Uso incorrecto del operador de referencia inversa.
Uso incorrecto de operadores de patrón tales como grupo o lista.
Invalid use of repetition operators such as using '*' as the first character.
Existe una llave de un operador de intervalo no emparejada.
Existe un corchete de un operador de lista no emparejado.
Elemento de comparación inválido.
Nombre de clase de caracteres desconocido.
Error indefinido. No definido por POSIX.2.
Barra invertida (\) al final.
Existe un paréntesis de un operador de grupo no emparejado.
Uso incorrecto de un operador de rango; por ejemplo, el límite superior del rango ocurre antes que el límite inferior.
La expresión regular compilada necesita un buffer de patrones mayor que 64 kB. No definido por POSIX.2.
Las rutinas de expresiones regulares se ejecutaron fuera de sus límites de memoria.
Referencia inversa incorrecta a una subexpresión.

ATRIBUTOS

Para obtener una explicación de los términos usados en esta sección, véase attributes(7).

Interfaz Atributo Valor
regcomp(), regexec() Seguridad del hilo Configuración regional de multi-hilo seguro
regerror() Seguridad del hilo MT-Safe env
regfree() Seguridad del hilo Multi-hilo seguro

ESTÁNDARES

POSIX.1-2001, POSIX.1-2008.

EJEMPLOS

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <regex.h>
#define ARRAY_SIZE(arr) (sizeof((arr)) / sizeof((arr)[0]))
static const char *const str =

"1) John Driverhacker;\n2) John Doe;\n3) John Foo;\n"; static const char *const re = "John.*o"; int main(void) {
static const char *s = str;
regex_t regex;
regmatch_t pmatch[1];
regoff_t off, len;
if (regcomp(&regex, re, REG_NEWLINE))
exit(EXIT_FAILURE);
printf("String = \"%s\"\n", str);
printf("Matches:\n");
for (unsigned int i = 0; ; i++) {
if (regexec(&regex, s, ARRAY_SIZE(pmatch), pmatch, 0))
break;
off = pmatch[0].rm_so + (s - str);
len = pmatch[0].rm_eo - pmatch[0].rm_so;
printf("#%zu:\n", i);
printf("offset = %jd; length = %jd\n", (intmax_t) off,
(intmax_t) len);
printf("substring = \"%.*s\"\n", len, s + pmatch[0].rm_so);
s += pmatch[0].rm_eo;
}
exit(EXIT_SUCCESS); }

VÉASE TAMBIÉN

grep(1), regex(7)

The glibc manual section, Regular Expressions

TRADUCCIÓN

La traducción al español de esta página del manual fue creada por Juan Piernas <piernas@ditec.um.es>

Esta traducción es documentación libre; lea la GNU General Public License Version 3 o posterior con respecto a las condiciones de copyright. No existe NINGUNA RESPONSABILIDAD.

Si encuentra algún error en la traducción de esta página del manual, envíe un correo electrónico a debian-l10n-spanish@lists.debian.org.

5 Febrero 2023 Páginas de manual de Linux 6.03