# Copyright (C) 2001-2020, Python Software Foundation # This file is distributed under the same license as the Python package. # Maintained by the python-doc-es workteam. # docs-es@python.org / # https://mail.python.org/mailman3/lists/docs-es.python.org/ # Check https://github.com/python/python-docs-es/blob/3.8/TRANSLATORS to # get the list of volunteers # msgid "" msgstr "" "Project-Id-Version: Python 3.8\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2022-10-25 19:47+0200\n" "PO-Revision-Date: 2021-08-04 17:34+0200\n" "Last-Translator: Cristián Maureira-Fredes \n" "Language: es\n" "Language-Team: python-doc-es\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" "Generated-By: Babel 2.10.3\n" #: ../Doc/howto/regex.rst:5 msgid "Regular Expression HOWTO" msgstr "Expresiones regulares COMOS (*HOWTO*)" #: ../Doc/howto/regex.rst msgid "Author" msgstr "Autor" #: ../Doc/howto/regex.rst:7 msgid "A.M. Kuchling " msgstr "*A.M. Kuchling *" msgid "Abstract" msgstr "Resumen" #: ../Doc/howto/regex.rst:18 msgid "" "This document is an introductory tutorial to using regular expressions in " "Python with the :mod:`re` module. It provides a gentler introduction than " "the corresponding section in the Library Reference." msgstr "" "Este documento es un tutorial de introducción al uso de expresiones " "regulares en Python con el módulo :mod:`re`. Proporciona una introducción " "más apacible que la sección correspondiente en la Referencia de la " "Biblioteca." #: ../Doc/howto/regex.rst:24 msgid "Introduction" msgstr "Introducción" #: ../Doc/howto/regex.rst:26 msgid "" "Regular expressions (called REs, or regexes, or regex patterns) are " "essentially a tiny, highly specialized programming language embedded inside " "Python and made available through the :mod:`re` module. Using this little " "language, you specify the rules for the set of possible strings that you " "want to match; this set might contain English sentences, or e-mail " "addresses, or TeX commands, or anything you like. You can then ask " "questions such as \"Does this string match the pattern?\", or \"Is there a " "match for the pattern anywhere in this string?\". You can also use REs to " "modify a string or to split it apart in various ways." msgstr "" "Las expresiones regulares (llamadas RE, o regex, o patrones de regex) son " "esencialmente en un lenguaje de programación diminuto y altamente " "especializado incrustado dentro de Python y disponible a través del módulo :" "mod:`re`. Usando este pequeño lenguaje, especificas las reglas para el " "conjunto de cadenas de caracteres posibles que deseas hacer coincidir; este " "conjunto puede contener frases en inglés, o direcciones de correo " "electrónico, o comandos TeX, o cualquier cosa que desee. A continuación, " "puede hacer preguntas como \"¿Coincide esta cadena con el patrón?\" o \"¿Hay " "alguna coincidencia con el patrón en alguna parte de esta cadena?\". También " "puede utilizar RE para modificar una cadena de caracteres o dividirla de " "varias formas." #: ../Doc/howto/regex.rst:35 msgid "" "Regular expression patterns are compiled into a series of bytecodes which " "are then executed by a matching engine written in C. For advanced use, it " "may be necessary to pay careful attention to how the engine will execute a " "given RE, and write the RE in a certain way in order to produce bytecode " "that runs faster. Optimization isn't covered in this document, because it " "requires that you have a good understanding of the matching engine's " "internals." msgstr "" "Los patrones de expresiones regulares se compilan en una serie de códigos de " "bytes que luego son ejecutados por un motor de coincidencia escrito en C. " "Para un uso avanzado, puede ser necesario prestar mucha atención a cómo el " "motor ejecutará una RE dado y escribir la RE en un de cierta manera para " "producir un código de bytes que se ejecute más rápido. La optimización no se " "trata en este documento, porque requiere que tenga un buen conocimiento de " "los componentes internos del motor de coincidencia." #: ../Doc/howto/regex.rst:42 msgid "" "The regular expression language is relatively small and restricted, so not " "all possible string processing tasks can be done using regular expressions. " "There are also tasks that *can* be done with regular expressions, but the " "expressions turn out to be very complicated. In these cases, you may be " "better off writing Python code to do the processing; while Python code will " "be slower than an elaborate regular expression, it will also probably be " "more understandable." msgstr "" "El lenguaje de expresiones regulares es relativamente pequeño y restringido, " "por lo que no todas las posibles tareas de procesamiento de cadenas de " "caracteres se pueden realizar utilizando expresiones regulares. También hay " "tareas que *se pueden* hacer con expresiones regulares, pero las expresiones " "resultan ser muy complicadas. En estos casos, es mejor que escriba código " "Python para realizar el procesamiento; Si bien el código Python será más " "lento que una expresión regular elaborada, probablemente también será más " "comprensible." #: ../Doc/howto/regex.rst:51 msgid "Simple Patterns" msgstr "Patrones simples" #: ../Doc/howto/regex.rst:53 msgid "" "We'll start by learning about the simplest possible regular expressions. " "Since regular expressions are used to operate on strings, we'll begin with " "the most common task: matching characters." msgstr "" "Comenzaremos aprendiendo sobre las expresiones regulares más simples " "posibles. Dado que las expresiones regulares se utilizan para operar en " "cadenas de caracteres, comenzaremos con la tarea más común: hacer coincidir " "caracteres." #: ../Doc/howto/regex.rst:57 msgid "" "For a detailed explanation of the computer science underlying regular " "expressions (deterministic and non-deterministic finite automata), you can " "refer to almost any textbook on writing compilers." msgstr "" "Para obtener una explicación detallada de la informática que subyace a las " "expresiones regulares (autómatas finitos deterministas y no deterministas), " "puede consultar casi cualquier libro de texto sobre la escritura de " "compiladores." #: ../Doc/howto/regex.rst:63 msgid "Matching Characters" msgstr "Coincidencia de Caracteres (*Matching Characters*)" #: ../Doc/howto/regex.rst:65 msgid "" "Most letters and characters will simply match themselves. For example, the " "regular expression ``test`` will match the string ``test`` exactly. (You " "can enable a case-insensitive mode that would let this RE match ``Test`` or " "``TEST`` as well; more about this later.)" msgstr "" "La mayoría de letras y caracteres simplemente coincidirán. Por ejemplo, la " "expresión regular ``test`` coincidirá exactamente con la cadena ``test``. " "(Puede habilitar un modo que no distinga entre mayúsculas y minúsculas que " "permitiría que este RE coincida con ``test`` o ``TEST`` también; más sobre " "esto más adelante.)" #: ../Doc/howto/regex.rst:70 msgid "" "There are exceptions to this rule; some characters are special :dfn:" "`metacharacters`, and don't match themselves. Instead, they signal that " "some out-of-the-ordinary thing should be matched, or they affect other " "portions of the RE by repeating them or changing their meaning. Much of " "this document is devoted to discussing various metacharacters and what they " "do." msgstr "" "Hay excepciones a esta regla; algunos caracteres son especiales :dfn:" "`metacharacters`, y no coinciden. En cambio, señalan que debe coincidir con " "algo fuera de lo común, o afectan otras partes de la RE repitiéndolos o " "cambiando su significado. Gran parte de este documento está dedicado a " "discutir varios metacarácteres y lo que hacen." #: ../Doc/howto/regex.rst:76 msgid "" "Here's a complete list of the metacharacters; their meanings will be " "discussed in the rest of this HOWTO." msgstr "" "Aquí hay una lista completa de los metacarácteres; sus significados se " "discutirán en el resto de este COMO (*HOWTO*)." #: ../Doc/howto/regex.rst:83 msgid "" "The first metacharacters we'll look at are ``[`` and ``]``. They're used for " "specifying a character class, which is a set of characters that you wish to " "match. Characters can be listed individually, or a range of characters can " "be indicated by giving two characters and separating them by a ``'-'``. For " "example, ``[abc]`` will match any of the characters ``a``, ``b``, or ``c``; " "this is the same as ``[a-c]``, which uses a range to express the same set of " "characters. If you wanted to match only lowercase letters, your RE would be " "``[a-z]``." msgstr "" "Los primeros metacarácteres que veremos son ``[`` and ``]``. Se utilizan " "para especificar una clase de carácter, que es un conjunto de caracteres que " "desea hacer coincidir. Los caracteres se pueden enumerar individualmente, o " "se puede indicar un rango de caracteres dando dos caracteres y separándolos " "con un ``'-'``. Por ejemplo, ``[abc]`` coincidirá con cualquiera de los " "caracteres ``a``, ``b`` o ``c``; esto es lo mismo que ``[a-c]``, que usa un " "rango para expresar el mismo conjunto de caracteres. Si quisiera hacer " "coincidir solo letras minúsculas, su RE sería ``[a-c]``." #: ../Doc/howto/regex.rst:92 #, fuzzy msgid "" "Metacharacters (except ``\\``) are not active inside classes. For example, " "``[akm$]`` will match any of the characters ``'a'``, ``'k'``, ``'m'``, or " "``'$'``; ``'$'`` is usually a metacharacter, but inside a character class " "it's stripped of its special nature." msgstr "" "Los metacarácteres no están activos dentro de las clases. Por ejemplo, " "``[akm$]`` coincidirá con cualquiera de los caracteres ``'a'``, ``'k'``, " "``'m'``, or ``'$'``; ``'$'`` suele ser un metacarácter, pero dentro de una " "clase de carácter se le quita su naturaleza especial." #: ../Doc/howto/regex.rst:97 msgid "" "You can match the characters not listed within the class by :dfn:" "`complementing` the set. This is indicated by including a ``'^'`` as the " "first character of the class. For example, ``[^5]`` will match any character " "except ``'5'``. If the caret appears elsewhere in a character class, it " "does not have special meaning. For example: ``[5^]`` will match either a " "``'5'`` or a ``'^'``." msgstr "" "Puede hacer coincidir los caracteres que no figuran en la clase mediante el " "conjunto :dfn:`complementing`. Esto se indica mediante la inclusión de un " "``'^'`` como primer carácter de la clase. Por ejemplo, ``[^5]`` coincidirá " "con cualquier carácter excepto con ``'5'``. Si el símbolo de intercalación " "aparece en otra parte de una clase de caracter, no tiene un significado " "especial. Por ejemplo: ``[5^] `` coincidirá con un ``'5'`` o un ``'^'``." #: ../Doc/howto/regex.rst:103 msgid "" "Perhaps the most important metacharacter is the backslash, ``\\``. As in " "Python string literals, the backslash can be followed by various characters " "to signal various special sequences. It's also used to escape all the " "metacharacters so you can still match them in patterns; for example, if you " "need to match a ``[`` or ``\\``, you can precede them with a backslash to " "remove their special meaning: ``\\[`` or ``\\\\``." msgstr "" "Quizás el metacarácter más importante es la barra invertida, ``\\``. Al " "igual que en los literales de cadena de Python, la barra invertida puede ir " "seguida de varios caracteres para señalar varias secuencias especiales. " "También se usa para escapar de todos los metacarácteres, de modo que aún " "pueda emparejarlos en patrones; por ejemplo, si necesita hacer coincidir un " "``[`` o ``\\``, puede precederlos con una barra invertida para eliminar su " "significado especial: ``\\[`` o ``\\\\``." #: ../Doc/howto/regex.rst:110 msgid "" "Some of the special sequences beginning with ``'\\'`` represent predefined " "sets of characters that are often useful, such as the set of digits, the set " "of letters, or the set of anything that isn't whitespace." msgstr "" "Algunas de las secuencias especiales que comienzan con ``'\\'`` representan " "conjuntos predefinidos de caracteres que a menudo son útiles, como el " "conjunto de dígitos, el conjunto de letras o el conjunto de cualquier cosa " "que no sea un espacio en blanco." #: ../Doc/howto/regex.rst:115 msgid "" "Let's take an example: ``\\w`` matches any alphanumeric character. If the " "regex pattern is expressed in bytes, this is equivalent to the class ``[a-zA-" "Z0-9_]``. If the regex pattern is a string, ``\\w`` will match all the " "characters marked as letters in the Unicode database provided by the :mod:" "`unicodedata` module. You can use the more restricted definition of ``\\w`` " "in a string pattern by supplying the :const:`re.ASCII` flag when compiling " "the regular expression." msgstr "" "Tomemos un ejemplo: ``\\w`` coincide con cualquier carácter alfanumérico. Si " "el patrón de expresiones regulares se expresa en bytes, esto es equivalente " "a la clase ``[a-zA-Z0-9_]``. Si el patrón de expresiones regulares es una " "cadena de caracteres, ``\\w`` coincidirá con todos los caracteres marcados " "como letras en la base de datos Unicode proporcionada por el módulo :mod:" "`unicodedata`. Puede usar la definición más restringida de ``\\w`` en un " "patrón de cadena proporcionando el indicador :const:`re.ASCII` al compilar " "la expresión regular." #: ../Doc/howto/regex.rst:123 msgid "" "The following list of special sequences isn't complete. For a complete list " "of sequences and expanded class definitions for Unicode string patterns, see " "the last part of :ref:`Regular Expression Syntax ` in the " "Standard Library reference. In general, the Unicode versions match any " "character that's in the appropriate category in the Unicode database." msgstr "" "La siguiente lista de secuencias especiales no está completa. Para obtener " "una lista completa de secuencias y definiciones de clases expandidas para " "patrones de cadenas Unicode, consulte la última parte de :ref:`Regular " "Expression Syntax ` en la referencia de la biblioteca estándar. " "En general, las versiones Unicode coinciden con cualquier carácter que esté " "en la categoría apropiada en la base de datos Unicode." #: ../Doc/howto/regex.rst:131 msgid "``\\d``" msgstr "``\\d``" #: ../Doc/howto/regex.rst:131 msgid "Matches any decimal digit; this is equivalent to the class ``[0-9]``." msgstr "" "Coincide con cualquier dígito decimal; esto es equivalente a la clase " "``[0-9]``." #: ../Doc/howto/regex.rst:134 msgid "``\\D``" msgstr "``\\D``" #: ../Doc/howto/regex.rst:134 msgid "" "Matches any non-digit character; this is equivalent to the class ``[^0-9]``." msgstr "" "Coincide con cualquier carácter que no sea un dígito; esto es equivalente a " "la clase ``[^0-9]``." #: ../Doc/howto/regex.rst:138 msgid "``\\s``" msgstr "``\\s``" #: ../Doc/howto/regex.rst:137 msgid "" "Matches any whitespace character; this is equivalent to the class " "``[ \\t\\n\\r\\f\\v]``." msgstr "" "Coincide con cualquier carácter de espacio en blanco; esto es equivalente a " "la clase ``[ \\t\\n\\r\\f\\v]``." #: ../Doc/howto/regex.rst:142 msgid "``\\S``" msgstr "``\\S``" #: ../Doc/howto/regex.rst:141 msgid "" "Matches any non-whitespace character; this is equivalent to the class ``[^ " "\\t\\n\\r\\f\\v]``." msgstr "" "Coincide con cualquier carácter que no sea un espacio en blanco; esto es " "equivalente a la clase ``[^ \\t\\n\\r\\f\\v]``." #: ../Doc/howto/regex.rst:146 msgid "``\\w``" msgstr "``\\w``" #: ../Doc/howto/regex.rst:145 msgid "" "Matches any alphanumeric character; this is equivalent to the class ``[a-zA-" "Z0-9_]``." msgstr "" "Coincide con cualquier carácter alfanumérico; esto es equivalente a la clase " "``[a-zA-Z0-9_]``." #: ../Doc/howto/regex.rst:150 msgid "``\\W``" msgstr "``\\W``" #: ../Doc/howto/regex.rst:149 msgid "" "Matches any non-alphanumeric character; this is equivalent to the class " "``[^a-zA-Z0-9_]``." msgstr "" "Coincide con cualquier carácter no alfanumérico; esto es equivalente a la " "clase ``[^a-zA-Z0-9_]``." #: ../Doc/howto/regex.rst:152 msgid "" "These sequences can be included inside a character class. For example, " "``[\\s,.]`` is a character class that will match any whitespace character, " "or ``','`` or ``'.'``." msgstr "" "Estas secuencias se pueden incluir dentro de una clase de carácter. Por " "ejemplo, ``[\\s,.]`` es una clase de carácter que coincidirá con cualquier " "carácter de espacio en blanco, o ``','`` o ``'.'``." #: ../Doc/howto/regex.rst:156 msgid "" "The final metacharacter in this section is ``.``. It matches anything " "except a newline character, and there's an alternate mode (:const:`re." "DOTALL`) where it will match even a newline. ``.`` is often used where you " "want to match \"any character\"." msgstr "" "El metacarácter final en esta sección es ``.``. Coincide con cualquier cosa " "excepto un carácter de nueva línea, y hay un modo alternativo (:const:`re." "DOTALL`) donde coincidirá incluso con una nueva línea. ``.`` se usa a menudo " "cuando se desea hacer coincidir \"cualquier carácter\"." #: ../Doc/howto/regex.rst:163 msgid "Repeating Things" msgstr "Repitiendo cosas" #: ../Doc/howto/regex.rst:165 msgid "" "Being able to match varying sets of characters is the first thing regular " "expressions can do that isn't already possible with the methods available on " "strings. However, if that was the only additional capability of regexes, " "they wouldn't be much of an advance. Another capability is that you can " "specify that portions of the RE must be repeated a certain number of times." msgstr "" "Ser capaz de hacer coincidir diferentes conjuntos de caracteres es lo " "primero que pueden hacer las expresiones regulares que ya no es posible con " "los métodos disponibles en cadenas de caracteres. Sin embargo, si esa fuera " "la única capacidad adicional de las expresiones regulares, no serían un gran " "avance. Otra capacidad es que puede especificar que partes de la RE deben " "repetirse un cierto número de veces." #: ../Doc/howto/regex.rst:171 msgid "" "The first metacharacter for repeating things that we'll look at is ``*``. " "``*`` doesn't match the literal character ``'*'``; instead, it specifies " "that the previous character can be matched zero or more times, instead of " "exactly once." msgstr "" "El primer metacarácter para repetir cosas que veremos es ``*``. ``*`` no " "coincide con el carácter literal ``'*'``; en cambio, especifica que el " "carácter anterior puede coincidir cero o más veces, en lugar de exactamente " "una vez." #: ../Doc/howto/regex.rst:175 msgid "" "For example, ``ca*t`` will match ``'ct'`` (0 ``'a'`` characters), ``'cat'`` " "(1 ``'a'``), ``'caaat'`` (3 ``'a'`` characters), and so forth." msgstr "" "Por ejemplo, ``ca*t`` coincidirá con ``'ct'`` (0 ``'a'`` caracteres), " "``'cat'`` (1 ``'a'``), ``'caaat'`` (3 ``'a'`` caracteres), etc." #: ../Doc/howto/regex.rst:178 msgid "" "Repetitions such as ``*`` are :dfn:`greedy`; when repeating a RE, the " "matching engine will try to repeat it as many times as possible. If later " "portions of the pattern don't match, the matching engine will then back up " "and try again with fewer repetitions." msgstr "" "Las repeticiones como ``*`` son :dfn:`greedy`; al repetir una RE, el motor " "de emparejamiento intentará repetirlo tantas veces como sea posible. Si las " "partes posteriores del patrón no coinciden, el motor de coincidencia hará " "una copia de seguridad y volverá a intentarlo con menos repeticiones." #: ../Doc/howto/regex.rst:183 msgid "" "A step-by-step example will make this more obvious. Let's consider the " "expression ``a[bcd]*b``. This matches the letter ``'a'``, zero or more " "letters from the class ``[bcd]``, and finally ends with a ``'b'``. Now " "imagine matching this RE against the string ``'abcbd'``." msgstr "" "Un ejemplo paso a paso hará que esto sea más obvio. Consideremos la " "expresión ``a[bcd]*b``. Esto coincide con la letra ``'a'``, cero o más " "letras de la clase ``[bcd]``, y finalmente termina con una ``'b'``. Ahora " "imagina hacer coincidir este RE con la cadena de caracteres ``'abcbd'``." #: ../Doc/howto/regex.rst:189 msgid "Step" msgstr "Pasos" #: ../Doc/howto/regex.rst:189 msgid "Matched" msgstr "Coincidencias" #: ../Doc/howto/regex.rst:189 msgid "Explanation" msgstr "Explicación" #: ../Doc/howto/regex.rst:191 msgid "1" msgstr "1" #: ../Doc/howto/regex.rst:191 msgid "``a``" msgstr "``a``" #: ../Doc/howto/regex.rst:191 msgid "The ``a`` in the RE matches." msgstr "La ``a`` en las RE coincide." #: ../Doc/howto/regex.rst:193 msgid "2" msgstr "2" #: ../Doc/howto/regex.rst:193 msgid "``abcbd``" msgstr "``abcbd``" #: ../Doc/howto/regex.rst:193 msgid "" "The engine matches ``[bcd]*``, going as far as it can, which is to the end " "of the string." msgstr "" "El motor coincide con ``[bcd]*``, yendo tan lejos como puede, que es hasta " "el final de la cadena de caracteres." #: ../Doc/howto/regex.rst:197 msgid "3" msgstr "3" #: ../Doc/howto/regex.rst:197 ../Doc/howto/regex.rst:205 msgid "*Failure*" msgstr "*Failure*" #: ../Doc/howto/regex.rst:197 msgid "" "The engine tries to match ``b``, but the current position is at the end of " "the string, so it fails." msgstr "" "El motor intenta hacer coincidir ``b``, pero la posición actual está al " "final de la cadena de caracteres, por lo que falla." #: ../Doc/howto/regex.rst:202 msgid "4" msgstr "4" #: ../Doc/howto/regex.rst:202 ../Doc/howto/regex.rst:213 msgid "``abcb``" msgstr "``abcb``" #: ../Doc/howto/regex.rst:202 msgid "Back up, so that ``[bcd]*`` matches one less character." msgstr "" "Hace una copia de seguridad para que ``[bcd]*`` coincida con un carácter " "menos." #: ../Doc/howto/regex.rst:205 msgid "5" msgstr "5" #: ../Doc/howto/regex.rst:205 msgid "" "Try ``b`` again, but the current position is at the last character, which is " "a ``'d'``." msgstr "" "Intente ``b`` de nuevo, pero la posición actual está en el último caracter, " "que es un ``'d'``." #: ../Doc/howto/regex.rst:209 ../Doc/howto/regex.rst:213 msgid "6" msgstr "6" #: ../Doc/howto/regex.rst:209 msgid "``abc``" msgstr "``abc``" #: ../Doc/howto/regex.rst:209 msgid "Back up again, so that ``[bcd]*`` is only matching ``bc``." msgstr "" "Haga una copia de seguridad de nuevo, de modo que ``[bcd]*`` solo coincida " "con ``bc``." #: ../Doc/howto/regex.rst:213 msgid "" "Try ``b`` again. This time the character at the current position is " "``'b'``, so it succeeds." msgstr "" "Intente ``b`` de nuevo. Esta vez, el carácter en la posición actual es " "``'b'``, por lo que tiene éxito." #: ../Doc/howto/regex.rst:219 msgid "" "The end of the RE has now been reached, and it has matched ``'abcb'``. This " "demonstrates how the matching engine goes as far as it can at first, and if " "no match is found it will then progressively back up and retry the rest of " "the RE again and again. It will back up until it has tried zero matches for " "``[bcd]*``, and if that subsequently fails, the engine will conclude that " "the string doesn't match the RE at all." msgstr "" "Se ha alcanzado el final de la RE y ha coincidido con ``'abcb'``. Esto " "demuestra cómo el motor de coincidencias llega tan lejos como puede al " "principio, y si no se encuentra ninguna coincidencia, retrocederá " "progresivamente y volverá a intentar de la RE una y otra vez. Hará una copia " "de seguridad hasta que haya probado cero coincidencias para ``[bcd]*``, y si " "eso falla posteriormente, el motor concluirá que la cadena no coincide con " "la RE en absoluto." #: ../Doc/howto/regex.rst:226 msgid "" "Another repeating metacharacter is ``+``, which matches one or more times. " "Pay careful attention to the difference between ``*`` and ``+``; ``*`` " "matches *zero* or more times, so whatever's being repeated may not be " "present at all, while ``+`` requires at least *one* occurrence. To use a " "similar example, ``ca+t`` will match ``'cat'`` (1 ``'a'``), ``'caaat'`` (3 " "``'a'``\\ s), but won't match ``'ct'``." msgstr "" "Otro metacarácter que se repite es ``+``, que coincide una o más veces. " "Preste especial atención a la diferencia entre ``*`` and ``+``; coincide con " "*cero* o más veces, por lo que cualquier cosa que se repita puede no estar " "presente en absoluto, mientras que ``+`` requiere al menos *one* aparición. " "Para usar un ejemplo similar, ``'cat'`` (1 ``'a'``), ``'caaat'`` (3 " "``'a'``\\ s), pero no coincidirá con ``'ct'``." #: ../Doc/howto/regex.rst:233 #, fuzzy msgid "" "There are two more repeating operators or quantifiers. The question mark " "character, ``?``, matches either once or zero times; you can think of it as " "marking something as being optional. For example, ``home-?brew`` matches " "either ``'homebrew'`` or ``'home-brew'``." msgstr "" "Hay dos calificadores más que se repiten. El carácter de signo de " "interrogación, ``?``, Coincide una vez o cero veces; puede pensar en ello " "como si marcara algo como opcional. Por ejemplo, ``home-?brew`` coincide con " "``'homebrew'`` o ``'home-brew'``." #: ../Doc/howto/regex.rst:238 #, fuzzy msgid "" "The most complicated quantifier is ``{m,n}``, where *m* and *n* are decimal " "integers. This quantifier means there must be at least *m* repetitions, and " "at most *n*. For example, ``a/{1,3}b`` will match ``'a/b'``, ``'a//b'``, " "and ``'a///b'``. It won't match ``'ab'``, which has no slashes, or ``'a////" "b'``, which has four." msgstr "" "El calificador repetido más complicado es ``{m,n}``, donde *m* y *n* son " "enteros decimales. Este calificador significa que debe haber al menos *m* " "repeticiones y como máximo *n*. Por ejemplo, ``a/{1,3}b`` coincidirá con``'a/" "b'``, ``'a//b'``, and ``'a///b'``. No coincidirá con `` 'ab' ', que no tiene " "barras, ni con ``'a////b'``, que tiene cuatro." #: ../Doc/howto/regex.rst:244 msgid "" "You can omit either *m* or *n*; in that case, a reasonable value is assumed " "for the missing value. Omitting *m* is interpreted as a lower limit of 0, " "while omitting *n* results in an upper bound of infinity." msgstr "" "Puede omitir *m* o *n*; en ese caso, se asume un valor razonable para el " "valor faltante. Omitir *m* se interpreta como un límite inferior de 0, " "mientras que omitir *n* da como resultado un límite superior de infinito." #: ../Doc/howto/regex.rst:248 #, fuzzy msgid "" "Readers of a reductionist bent may notice that the three other quantifiers " "can all be expressed using this notation. ``{0,}`` is the same as ``*``, " "``{1,}`` is equivalent to ``+``, and ``{0,1}`` is the same as ``?``. It's " "better to use ``*``, ``+``, or ``?`` when you can, simply because they're " "shorter and easier to read." msgstr "" "Los lectores de una inclinación reduccionista pueden notar que los otros " "tres calificativos pueden expresarse usando esta notación. ``{0,}`` es lo " "mismo que ``*``, ``{1,}`` es equivalente a ``+``, y ``{0,1}`` es lo mismo " "que ``?``. Es mejor usar ``*``, ``+``, o ``?`` cuando pueda, simplemente " "porque son más cortos y fáciles de leer." #: ../Doc/howto/regex.rst:256 msgid "Using Regular Expressions" msgstr "Usando Expresiones Regulares" #: ../Doc/howto/regex.rst:258 msgid "" "Now that we've looked at some simple regular expressions, how do we actually " "use them in Python? The :mod:`re` module provides an interface to the " "regular expression engine, allowing you to compile REs into objects and then " "perform matches with them." msgstr "" "Ahora que hemos visto algunas expresiones regulares simples, ¿cómo las " "usamos realmente en Python? El módulo :mod:`re` proporciona una interfaz " "para el motor de expresiones regulares, lo que le permite compilar RE en " "objetos y luego realizar coincidencias con ellos." #: ../Doc/howto/regex.rst:265 msgid "Compiling Regular Expressions" msgstr "Compilando Expresiones regulares" #: ../Doc/howto/regex.rst:267 msgid "" "Regular expressions are compiled into pattern objects, which have methods " "for various operations such as searching for pattern matches or performing " "string substitutions. ::" msgstr "" "Las expresiones regulares se compilan en objetos de patrón, que tienen " "métodos para diversas operaciones, como buscar coincidencias de patrones o " "realizar sustituciones de cadenas de caracteres. ::" #: ../Doc/howto/regex.rst:276 msgid "" ":func:`re.compile` also accepts an optional *flags* argument, used to enable " "various special features and syntax variations. We'll go over the available " "settings later, but for now a single example will do::" msgstr "" ":func:`re.compile` también acepta un argumento opcional *flags*, usado para " "habilitar varias características especiales y variaciones de sintaxis. " "Repasaremos las configuraciones disponibles más adelante, pero por ahora un " "solo ejemplo servirá:" #: ../Doc/howto/regex.rst:282 msgid "" "The RE is passed to :func:`re.compile` as a string. REs are handled as " "strings because regular expressions aren't part of the core Python language, " "and no special syntax was created for expressing them. (There are " "applications that don't need REs at all, so there's no need to bloat the " "language specification by including them.) Instead, the :mod:`re` module is " "simply a C extension module included with Python, just like the :mod:" "`socket` or :mod:`zlib` modules." msgstr "" "La RE se pasa a :func:`re.compile` como una cadena de caracteres. Las RE se " "manejan como cadenas de caracteres porque las expresiones regulares no son " "parte del lenguaje central de Python y no se creó una sintaxis especial para " "expresarlas. (Hay aplicaciones que no necesitan RE en absoluto, por lo que " "no hay necesidad de aumentar la especificación del lenguaje incluyéndolas). " "En cambio, el módulo :mod:`re` es simplemente un módulo de extensión C " "incluido en Python, al igual que los módulos :mod:`socket` o :mod:`zlib`." #: ../Doc/howto/regex.rst:289 msgid "" "Putting REs in strings keeps the Python language simpler, but has one " "disadvantage which is the topic of the next section." msgstr "" "Poner RE en cadenas de caracteres mantiene el lenguaje Python más simple, " "pero tiene una desventaja que es el tema de la siguiente sección." #: ../Doc/howto/regex.rst:296 msgid "The Backslash Plague" msgstr "La plaga de la barra invertida (*The Backslash Plague*)" #: ../Doc/howto/regex.rst:298 msgid "" "As stated earlier, regular expressions use the backslash character " "(``'\\'``) to indicate special forms or to allow special characters to be " "used without invoking their special meaning. This conflicts with Python's " "usage of the same character for the same purpose in string literals." msgstr "" "Como se indicó anteriormente, las expresiones regulares usan el carácter de " "barra invertida (``'\\'``) para indicar formas especiales o para permitir " "que se usen caracteres especiales sin invocar su significado especial. Esto " "entra en conflicto con el uso de Python del mismo carácter para el mismo " "propósito en cadenas literales." #: ../Doc/howto/regex.rst:303 msgid "" "Let's say you want to write a RE that matches the string ``\\section``, " "which might be found in a LaTeX file. To figure out what to write in the " "program code, start with the desired string to be matched. Next, you must " "escape any backslashes and other metacharacters by preceding them with a " "backslash, resulting in the string ``\\\\section``. The resulting string " "that must be passed to :func:`re.compile` must be ``\\\\section``. However, " "to express this as a Python string literal, both backslashes must be escaped " "*again*." msgstr "" "Supongamos que desea escribir una RE que coincida con la cadena de " "caracteres ``\\section``, que podría encontrarse en un archivo LaTeX. Para " "averiguar qué escribir en el código del programa, comience con la cadena " "deseada para que coincida. A continuación, debe escapar de las barras " "invertidas y otros metacarácteres precediéndolos con una barra invertida, lo " "que da como resultado la cadena ``\\\\section``. La cadena resultante que " "debe pasarse a :func:`re.compile` debe ser ``\\\\section``. Sin embargo, " "para expresar esto como una cadena literal de Python, ambas barras " "invertidas deben escaparse *nuevamente*." #: ../Doc/howto/regex.rst:312 msgid "Characters" msgstr "Caracteres" #: ../Doc/howto/regex.rst:312 msgid "Stage" msgstr "Explicación" #: ../Doc/howto/regex.rst:314 msgid "``\\section``" msgstr "``\\section``" #: ../Doc/howto/regex.rst:314 msgid "Text string to be matched" msgstr "Cadena de texto que debe coincidir" #: ../Doc/howto/regex.rst:316 msgid "``\\\\section``" msgstr "``\\\\section``" #: ../Doc/howto/regex.rst:316 msgid "Escaped backslash for :func:`re.compile`" msgstr "Barra invertida de escape para :func:`re.compile`" #: ../Doc/howto/regex.rst:318 ../Doc/howto/regex.rst:345 msgid "``\"\\\\\\\\section\"``" msgstr "``\"\\\\\\\\section\"``" #: ../Doc/howto/regex.rst:318 msgid "Escaped backslashes for a string literal" msgstr "Barra invertida de escape para un literal de cadena de caracteres" #: ../Doc/howto/regex.rst:321 msgid "" "In short, to match a literal backslash, one has to write ``'\\\\\\\\'`` as " "the RE string, because the regular expression must be ``\\\\``, and each " "backslash must be expressed as ``\\\\`` inside a regular Python string " "literal. In REs that feature backslashes repeatedly, this leads to lots of " "repeated backslashes and makes the resulting strings difficult to understand." msgstr "" "En resumen, para hacer coincidir una barra invertida literal, uno tiene que " "escribir ``'\\\\\\\\'`` como la cadena RE, porque la expresión regular debe " "ser ``\\\\``, y cada barra invertida debe expresarse como ``\\\\`` dentro de " "un literal de cadena Python normal. En las RE que presentan barras " "invertidas repetidamente, esto genera muchas barras invertidas repetidas y " "dificulta la comprensión de las cadenas resultantes." #: ../Doc/howto/regex.rst:327 msgid "" "The solution is to use Python's raw string notation for regular expressions; " "backslashes are not handled in any special way in a string literal prefixed " "with ``'r'``, so ``r\"\\n\"`` is a two-character string containing ``'\\'`` " "and ``'n'``, while ``\"\\n\"`` is a one-character string containing a " "newline. Regular expressions will often be written in Python code using this " "raw string notation." msgstr "" "La solución es utilizar la notación de cadena de caracteres sin formato de " "Python para expresiones regulares; las barras invertidas no se manejan de " "ninguna manera especial en una cadena literal con el prefijo ``'r'``, por lo " "que ``r\"\\n\"`` es una cadena de dos caracteres que contiene ``'\\'`` y " "``'n'``, mientras que ``\"\\n\"`` es una cadena de un carácter que contiene " "una nueva línea. Las expresiones regulares a menudo se escribirán en código " "Python utilizando esta notación de cadena sin formato." #: ../Doc/howto/regex.rst:333 msgid "" "In addition, special escape sequences that are valid in regular expressions, " "but not valid as Python string literals, now result in a :exc:" "`DeprecationWarning` and will eventually become a :exc:`SyntaxError`, which " "means the sequences will be invalid if raw string notation or escaping the " "backslashes isn't used." msgstr "" "Además, las secuencias de escape especiales que son válidas en expresiones " "regulares, pero no válidas como literales de cadena de Python, ahora dan " "como resultado :exc:`DeprecationWarning` y eventualmente se convertirán en :" "exc:`SyntaxError`, lo que significa que las secuencias no serán válidas. si " "no se utiliza la notación de cadena sin formato o el escape de las barras " "invertidas." #: ../Doc/howto/regex.rst:341 msgid "Regular String" msgstr "Cadena de caracteres regulares" #: ../Doc/howto/regex.rst:341 msgid "Raw string" msgstr "Cadena de caracteres crudas (*Raw string*)" #: ../Doc/howto/regex.rst:343 msgid "``\"ab*\"``" msgstr "``\"ab*\"``" #: ../Doc/howto/regex.rst:343 msgid "``r\"ab*\"``" msgstr "``r\"ab*\"``" #: ../Doc/howto/regex.rst:345 msgid "``r\"\\\\section\"``" msgstr "``r\"\\\\section\"``" #: ../Doc/howto/regex.rst:347 msgid "``\"\\\\w+\\\\s+\\\\1\"``" msgstr "``\"\\\\w+\\\\s+\\\\1\"``" #: ../Doc/howto/regex.rst:347 msgid "``r\"\\w+\\s+\\1\"``" msgstr "``r\"\\w+\\s+\\1\"``" #: ../Doc/howto/regex.rst:352 msgid "Performing Matches" msgstr "Realizando coincidencias" #: ../Doc/howto/regex.rst:354 msgid "" "Once you have an object representing a compiled regular expression, what do " "you do with it? Pattern objects have several methods and attributes. Only " "the most significant ones will be covered here; consult the :mod:`re` docs " "for a complete listing." msgstr "" "Una vez que tiene un objeto que representa una expresión regular compilada, " "¿qué hace con él? Los objetos de patrón tienen varios métodos y atributos. " "Aquí solo se cubrirán los más importantes; consulte los documentos :mod:`re` " "para obtener una lista completa." #: ../Doc/howto/regex.rst:360 ../Doc/howto/regex.rst:418 #: ../Doc/howto/regex.rst:1064 msgid "Method/Attribute" msgstr "Método/atributo" #: ../Doc/howto/regex.rst:360 ../Doc/howto/regex.rst:418 #: ../Doc/howto/regex.rst:1064 msgid "Purpose" msgstr "Objetivo" #: ../Doc/howto/regex.rst:362 msgid "``match()``" msgstr "``match()``" #: ../Doc/howto/regex.rst:362 msgid "Determine if the RE matches at the beginning of the string." msgstr "" "Determina si la RE coincide con el comienzo de la cadena de caracteres." #: ../Doc/howto/regex.rst:365 msgid "``search()``" msgstr "``search()``" #: ../Doc/howto/regex.rst:365 msgid "Scan through a string, looking for any location where this RE matches." msgstr "" "Escanea una cadena, buscando cualquier ubicación donde coincida este RE." #: ../Doc/howto/regex.rst:368 msgid "``findall()``" msgstr "``findall()``" #: ../Doc/howto/regex.rst:368 msgid "Find all substrings where the RE matches, and returns them as a list." msgstr "" "Encuentra todas las subcadenas de caracteres donde coincide la RE y las " "retorna como una lista." #: ../Doc/howto/regex.rst:371 msgid "``finditer()``" msgstr "``finditer()``" #: ../Doc/howto/regex.rst:371 msgid "" "Find all substrings where the RE matches, and returns them as an :term:" "`iterator`." msgstr "" "Encuentra todas las subcadenas donde la RE coincide y las retorna como un " "término iterado :term:`iterator`." #: ../Doc/howto/regex.rst:375 msgid "" ":meth:`~re.Pattern.match` and :meth:`~re.Pattern.search` return ``None`` if " "no match can be found. If they're successful, a :ref:`match object ` instance is returned, containing information about the match: " "where it starts and ends, the substring it matched, and more." msgstr "" ":meth:`~re.Pattern.match` y :meth:`~re.Pattern.search` retornan ``None`` si " "la coincidencia no puede ser encontrada. Si tienen éxito, se retorna una " "instancia :ref:`match object `, que contiene información " "sobre la coincidencia: dónde comienza y termina, la subcadena de caracteres " "con la que coincidió, y más." #: ../Doc/howto/regex.rst:380 msgid "" "You can learn about this by interactively experimenting with the :mod:`re` " "module. If you have :mod:`tkinter` available, you may also want to look at :" "source:`Tools/demo/redemo.py`, a demonstration program included with the " "Python distribution. It allows you to enter REs and strings, and displays " "whether the RE matches or fails. :file:`redemo.py` can be quite useful when " "trying to debug a complicated RE." msgstr "" "Puede aprender sobre esto experimentando interactivamente con el módulo :mod:" "`re`. Si tiene :mod:`tkinter` disponible, también puede consultar :source:" "`Tools/demo/redemo.py`, un programa de demostración incluido con la " "distribución de Python. Le permite ingresar RE y cadenas de caracteres, y " "muestra si la RE coincide o falla. :file:`redemo.py` puede ser bastante útil " "cuando se intenta depurar una RE complicado." #: ../Doc/howto/regex.rst:387 msgid "" "This HOWTO uses the standard Python interpreter for its examples. First, run " "the Python interpreter, import the :mod:`re` module, and compile a RE::" msgstr "" "Este CÓMO (*HOWTO*) utiliza el intérprete estándar de Python para sus " "ejemplos. Primero, ejecute el intérprete de Python, importe el módulo :mod:" "`re` y compile en RE::" #: ../Doc/howto/regex.rst:395 msgid "" "Now, you can try matching various strings against the RE ``[a-z]+``. An " "empty string shouldn't match at all, since ``+`` means 'one or more " "repetitions'. :meth:`~re.Pattern.match` should return ``None`` in this case, " "which will cause the interpreter to print no output. You can explicitly " "print the result of :meth:`!match` to make this clear. ::" msgstr "" "Ahora, puede intentar hacer coincidir varias cadenas con la RE ``[a-z]+``. " "Una cadena de caracteres vacía no debería coincidir en absoluto, ya que " "``+`` significa que 'una o más repeticiones'. :meth:`~re.Pattern.match` " "debería retornar ``None`` en este caso, lo que hará que el intérprete no " "imprima ningún resultado. Puede imprimir explícitamente el resultado de :" "meth:`!match` para aclarar esto. ::" #: ../Doc/howto/regex.rst:405 msgid "" "Now, let's try it on a string that it should match, such as ``tempo``. In " "this case, :meth:`~re.Pattern.match` will return a :ref:`match object `, so you should store the result in a variable for later use. ::" msgstr "" "Ahora, intentémoslo en una cadena de caracteres que debería coincidir, como " "``tempo``.En este caso , :meth:`~re.Pattern.match` retornará un :ref:`match " "object `, por lo que debe almacenar el resultado en una " "variable para su posterior uso. ::" #: ../Doc/howto/regex.rst:413 msgid "" "Now you can query the :ref:`match object ` for information " "about the matching string. Match object instances also have several methods " "and attributes; the most important ones are:" msgstr "" "Ahora puede consultar :ref:`match object ` para obtener " "información sobre la cadena coincidente. Las instancias de objetos " "coincidentes también tienen varios métodos y atributos; los más importantes " "son:" #: ../Doc/howto/regex.rst:420 msgid "``group()``" msgstr "``group()``" #: ../Doc/howto/regex.rst:420 msgid "Return the string matched by the RE" msgstr "Retorna la cadena de caracteres que coincide con la RE" #: ../Doc/howto/regex.rst:422 msgid "``start()``" msgstr "``start()``" #: ../Doc/howto/regex.rst:422 msgid "Return the starting position of the match" msgstr "Retorna la posición de inicio de la coincidencia" #: ../Doc/howto/regex.rst:424 msgid "``end()``" msgstr "``end()``" #: ../Doc/howto/regex.rst:424 msgid "Return the ending position of the match" msgstr "Retorna la posición final de la coincidencia" #: ../Doc/howto/regex.rst:426 msgid "``span()``" msgstr "``span()``" #: ../Doc/howto/regex.rst:426 msgid "Return a tuple containing the (start, end) positions of the match" msgstr "" "Retorna una tupla que contiene (inicio, final) las posiciones de coincidencia" #: ../Doc/howto/regex.rst:430 msgid "Trying these methods will soon clarify their meaning::" msgstr "Probando estos métodos pronto aclarará sus significados::" #: ../Doc/howto/regex.rst:439 msgid "" ":meth:`~re.Match.group` returns the substring that was matched by the RE. :" "meth:`~re.Match.start` and :meth:`~re.Match.end` return the starting and " "ending index of the match. :meth:`~re.Match.span` returns both start and end " "indexes in a single tuple. Since the :meth:`~re.Pattern.match` method only " "checks if the RE matches at the start of a string, :meth:`!start` will " "always be zero. However, the :meth:`~re.Pattern.search` method of patterns " "scans through the string, so the match may not start at zero in that " "case. ::" msgstr "" ":meth:`~re.Match.group` retorna la subcadena de caracteres que coincide con " "la RE. :meth:`~re.Match.start` y :meth:`~re.Match.end` retornan el índice " "inicial y final de la coincidencia. :meth:`~re.Match.span` retorna el índice " "inicial y final en una única tupla. Dado que el método :meth:`~re.Pattern." "match` solo verifica si la RE coincide al comienzo de una cadena de " "caracteres, :meth:`!start` siempre será cero. Sin embargo, el método de " "patrones :meth:`~re.Pattern.search` escanea a través de la cadena de " "caracteres, por lo que es posible que la coincidencia no comience en cero en " "ese caso. ::" #: ../Doc/howto/regex.rst:456 msgid "" "In actual programs, the most common style is to store the :ref:`match object " "` in a variable, and then check if it was ``None``. This " "usually looks like::" msgstr "" "En programas reales, el estilo más común es almacenar :ref:`match object " "` en una variable, y luego verificar si era ``None``. Esto " "generalmente se ve así::" #: ../Doc/howto/regex.rst:467 msgid "" "Two pattern methods return all of the matches for a pattern. :meth:`~re." "Pattern.findall` returns a list of matching strings::" msgstr "" "Dos métodos de patrón retornan todas las coincidencias de un patrón. :meth:" "`~re.Pattern.findall` retorna una lista de cadenas de caracteres " "coincidentes::" #: ../Doc/howto/regex.rst:474 msgid "" "The ``r`` prefix, making the literal a raw string literal, is needed in this " "example because escape sequences in a normal \"cooked\" string literal that " "are not recognized by Python, as opposed to regular expressions, now result " "in a :exc:`DeprecationWarning` and will eventually become a :exc:" "`SyntaxError`. See :ref:`the-backslash-plague`." msgstr "" "El prefijo ``r``, que convierte al literal en una cadena de caracteres " "literal sin formato, es necesario en este ejemplo porque las secuencias de " "escape en un cadena de caracteres literal \"cocinado\" normal que no son " "reconocidas por Python, a diferencia de las expresiones regulares, ahora dan " "como resultado :exc:`DeprecationWarning` y eventualmente se convertirá en :" "exc:`SyntaxError`. Ver :ref:`the-backslash-plague`." #: ../Doc/howto/regex.rst:480 msgid "" ":meth:`~re.Pattern.findall` has to create the entire list before it can be " "returned as the result. The :meth:`~re.Pattern.finditer` method returns a " "sequence of :ref:`match object ` instances as an :term:" "`iterator`::" msgstr "" ":meth:`~re.Pattern.findall` tiene que crear la lista completa antes de que " "pueda retornarse como resultado. El método :meth:`~re.Pattern.finditer` " "retorna una secuencia de :ref:`match object ` instancias como " "iterados :term:`iterator`::" #: ../Doc/howto/regex.rst:496 msgid "Module-Level Functions" msgstr "Funciones a nivel de módulo" #: ../Doc/howto/regex.rst:498 msgid "" "You don't have to create a pattern object and call its methods; the :mod:" "`re` module also provides top-level functions called :func:`~re.match`, :" "func:`~re.search`, :func:`~re.findall`, :func:`~re.sub`, and so forth. " "These functions take the same arguments as the corresponding pattern method " "with the RE string added as the first argument, and still return either " "``None`` or a :ref:`match object ` instance. ::" msgstr "" "No es necesario crear un objeto patrón y llamar a sus métodos; el módulo :" "mod:`re` también proporciona funciones de nivel superior llamadas :func:`~re." "match` , :func:`~re.search` , :func:`~re.findall` , :func:`~re.sub`, y así " "sucesivamente. Estas funciones toman los mismos argumentos que el método de " "patrón correspondiente con la cadena de RE agregada como primer argumento, y " "aún así retornan una instancia de ``None`` o :ref:`match object `. ::" #: ../Doc/howto/regex.rst:510 msgid "" "Under the hood, these functions simply create a pattern object for you and " "call the appropriate method on it. They also store the compiled object in a " "cache, so future calls using the same RE won't need to parse the pattern " "again and again." msgstr "" "Bajo el capó (*hood*), estas funciones simplemente crean un objeto patrón " "para usted y llaman al método apropiado en él. También almacenan el objeto " "compilado en un caché, por lo que las futuras llamadas que usen el mismo RE " "no necesitarán analizar el patrón una y otra vez." #: ../Doc/howto/regex.rst:515 msgid "" "Should you use these module-level functions, or should you get the pattern " "and call its methods yourself? If you're accessing a regex within a loop, " "pre-compiling it will save a few function calls. Outside of loops, there's " "not much difference thanks to the internal cache." msgstr "" "¿Debería utilizar estas funciones a nivel de módulo o debería obtener el " "patrón y llamar a sus métodos usted mismo? Si está accediendo a una " "expresión regular dentro de un bucle, la compilación previa guardará algunas " "llamadas a funciones. Fuera de los bucles, no hay mucha diferencia gracias " "al caché interno." #: ../Doc/howto/regex.rst:523 msgid "Compilation Flags" msgstr "Los Flags de compilación" #: ../Doc/howto/regex.rst:525 msgid "" "Compilation flags let you modify some aspects of how regular expressions " "work. Flags are available in the :mod:`re` module under two names, a long " "name such as :const:`IGNORECASE` and a short, one-letter form such as :const:" "`I`. (If you're familiar with Perl's pattern modifiers, the one-letter " "forms use the same letters; the short form of :const:`re.VERBOSE` is :const:" "`re.X`, for example.) Multiple flags can be specified by bitwise OR-ing " "them; ``re.I | re.M`` sets both the :const:`I` and :const:`M` flags, for " "example." msgstr "" "Las flags de compilación le permiten modificar algunos aspectos de cómo " "funcionan las expresiones regulares. Las flags están disponibles en el " "módulo :mod:`re` con dos nombres, un nombre largo como :const:`IGNORECASE` y " "una forma corta de una letra como :const:`I`. (Si está familiarizado con los " "modificadores de patrones de Perl, las formas de una letra usan las mismas " "letras; la forma corta de :const:`re.VERBOSE` es :const:`re.X`, por ejemplo)." "Se pueden especificar varios indicadores uniéndolos con *OR* bit a bit; ``re." "I | re.M`` establece los flags :const:`I` and :const:`M`, por ejemplo." #: ../Doc/howto/regex.rst:533 msgid "" "Here's a table of the available flags, followed by a more detailed " "explanation of each one." msgstr "" "Aquí hay una tabla de las flags disponibles, seguida de una explicación más " "detallada de cada una." #: ../Doc/howto/regex.rst:537 msgid "Flag" msgstr "Flag" #: ../Doc/howto/regex.rst:537 msgid "Meaning" msgstr "Significado" #: ../Doc/howto/regex.rst:539 msgid ":const:`ASCII`, :const:`A`" msgstr ":const:`ASCII`, :const:`A`" #: ../Doc/howto/regex.rst:539 msgid "" "Makes several escapes like ``\\w``, ``\\b``, ``\\s`` and ``\\d`` match only " "on ASCII characters with the respective property." msgstr "" "Hace que varios escapes como ``\\w``, ``\\b``, ``\\s`` y ``\\d`` coincidan " "solo en caracteres ASCII con la propiedad respectiva." #: ../Doc/howto/regex.rst:543 msgid ":const:`DOTALL`, :const:`S`" msgstr ":const:`DOTALL`, :const:`S`" #: ../Doc/howto/regex.rst:543 msgid "Make ``.`` match any character, including newlines." msgstr "" "Hace que ``.`` coincida con cualquier caracter, incluidas las nuevas líneas." #: ../Doc/howto/regex.rst:546 msgid ":const:`IGNORECASE`, :const:`I`" msgstr ":const:`IGNORECASE`, :const:`I`" #: ../Doc/howto/regex.rst:546 msgid "Do case-insensitive matches." msgstr "Hace coincidencias que no distingan entre mayúsculas y minúsculas." #: ../Doc/howto/regex.rst:548 msgid ":const:`LOCALE`, :const:`L`" msgstr ":const:`LOCALE`, :const:`L`" #: ../Doc/howto/regex.rst:548 msgid "Do a locale-aware match." msgstr "Hace una coincidencia con reconocimiento de configuración regional." #: ../Doc/howto/regex.rst:550 msgid ":const:`MULTILINE`, :const:`M`" msgstr ":const:`MULTILINE`, :const:`M`" #: ../Doc/howto/regex.rst:550 msgid "Multi-line matching, affecting ``^`` and ``$``." msgstr "Coincidencia de varias líneas, que afecta a ``^`` y ``$``." #: ../Doc/howto/regex.rst:553 msgid ":const:`VERBOSE`, :const:`X` (for 'extended')" msgstr ":const:`VERBOSE`, :const:`X` (for 'extended')" #: ../Doc/howto/regex.rst:553 msgid "" "Enable verbose REs, which can be organized more cleanly and understandably." msgstr "" "Habilite RE detallados, que se pueden organizar de manera más limpia y " "comprensible." #: ../Doc/howto/regex.rst:562 msgid "" "Perform case-insensitive matching; character class and literal strings will " "match letters by ignoring case. For example, ``[A-Z]`` will match lowercase " "letters, too. Full Unicode matching also works unless the :const:`ASCII` " "flag is used to disable non-ASCII matches. When the Unicode patterns ``[a-" "z]`` or ``[A-Z]`` are used in combination with the :const:`IGNORECASE` flag, " "they will match the 52 ASCII letters and 4 additional non-ASCII letters: " "'İ' (U+0130, Latin capital letter I with dot above), 'ı' (U+0131, Latin " "small letter dotless i), 'ſ' (U+017F, Latin small letter long s) and " "'K' (U+212A, Kelvin sign). ``Spam`` will match ``'Spam'``, ``'spam'``, " "``'spAM'``, or ``'ſpam'`` (the latter is matched only in Unicode mode). This " "lowercasing doesn't take the current locale into account; it will if you " "also set the :const:`LOCALE` flag." msgstr "" "Realiza una coincidencia que no distinga entre mayúsculas y minúsculas; la " "clase de caracteres y las cadenas de caracteres literales coincidirán con " "las letras ignorando las mayúsculas. Por ejemplo, ``[A-Z]`` también " "coincidirá con letras minúsculas. La coincidencia completa de Unicode " "también funciona a menos que se utilice la flag :const:`ASCII` para " "deshabilitar las coincidencias que no sean ASCII. Cuando los patrones " "Unicode ``[a-z]`` o ``[A-Z]`` se utilizan en combinación con el indicador :" "const:`IGNORECASE` , coincidirán con las 52 letras ASCII y 4 letras " "adicionales no ASCII 'İ' (U+0130, letra mayúscula latina I con un punto " "arriba), 'ı' (U+0131, letra minúscula latina sin punto i),'ſ' (U+017F, letra " "minúscula latina larga s) y 'K' (U+212A, signo de Kelvin). ``Spam`` " "coincidirá ``'Spam'``, ``'spam'``, ``'spAM'``, o ``'ſpam'`` (este último " "solo coincide en modo Unicode). Estas minúsculas no tiene en cuenta la " "configuración regional actual; lo hará si también establece la flag :const:" "`LOCALE` ." #: ../Doc/howto/regex.rst:580 msgid "" "Make ``\\w``, ``\\W``, ``\\b``, ``\\B`` and case-insensitive matching " "dependent on the current locale instead of the Unicode database." msgstr "" "Hace que ``\\w``, ``\\W``, ``\\b``, ``\\B`` y la coincidencia que no " "distinga entre mayúsculas y minúsculas dependan de la configuración regional " "actual en lugar de la base de datos Unicode." #: ../Doc/howto/regex.rst:583 msgid "" "Locales are a feature of the C library intended to help in writing programs " "that take account of language differences. For example, if you're " "processing encoded French text, you'd want to be able to write ``\\w+`` to " "match words, but ``\\w`` only matches the character class ``[A-Za-z]`` in " "bytes patterns; it won't match bytes corresponding to ``é`` or ``ç``. If " "your system is configured properly and a French locale is selected, certain " "C functions will tell the program that the byte corresponding to ``é`` " "should also be considered a letter. Setting the :const:`LOCALE` flag when " "compiling a regular expression will cause the resulting compiled object to " "use these C functions for ``\\w``; this is slower, but also enables ``\\w+`` " "to match French words as you'd expect. The use of this flag is discouraged " "in Python 3 as the locale mechanism is very unreliable, it only handles one " "\"culture\" at a time, and it only works with 8-bit locales. Unicode " "matching is already enabled by default in Python 3 for Unicode (str) " "patterns, and it is able to handle different locales/languages." msgstr "" "Las configuraciones regionales son una característica de la biblioteca C " "destinada a ayudar a escribir programas que tengan en cuenta las diferencias " "de idioma. Por ejemplo, si está procesando texto en francés codificado, " "querrá poder escribir ``\\w+`` para que coincida con las palabras, pero " "``\\w`` solo coincide con la clase de caracteres ``[A-Za-z]`` en patrones de " "bytes; no coincidirá con los bytes correspondientes a ``é`` or ``ç``. Si su " "sistema está configurado correctamente y se selecciona una configuración " "regional francesa, ciertas funciones de C le dirán al programa que el byte " "correspondiente a ``é`` también debe considerarse una letra. Establecer el " "indicador :const:`LOCALE` al compilar una expresión regular hará que el " "objeto compilado resultante use estas funciones C para ``\\w``; esto es más " "lento, pero también permite que ``\\w+`` coincida con las palabras en " "francés como era de esperar. Se desaconseja el uso de esta flag en Python 3 " "ya que el mecanismo de configuración regional es muy poco confiable, solo " "maneja una \"cultura\" a la vez y solo funciona con configuraciones " "regionales de 8 bits. La coincidencia Unicode ya está habilitada de forma " "predeterminada en Python 3 para patrones Unicode (str), y puede manejar " "diferentes configuraciones regionales/idiomas." #: ../Doc/howto/regex.rst:605 msgid "" "(``^`` and ``$`` haven't been explained yet; they'll be introduced in " "section :ref:`more-metacharacters`.)" msgstr "" "(``^`` y ``$`` aún no se han explicado; se presentarán en la sección :ref:" "`more-metacharacters`.)" #: ../Doc/howto/regex.rst:608 msgid "" "Usually ``^`` matches only at the beginning of the string, and ``$`` matches " "only at the end of the string and immediately before the newline (if any) at " "the end of the string. When this flag is specified, ``^`` matches at the " "beginning of the string and at the beginning of each line within the string, " "immediately following each newline. Similarly, the ``$`` metacharacter " "matches either at the end of the string and at the end of each line " "(immediately preceding each newline)." msgstr "" "Por lo general, ``^`` coincide solo al principio de la cadena de caracteres, " "y ``$`` solo coincide con el final de la cadena de caracteres e " "inmediatamente antes del salto de línea (si existe) al final de la cadena de " "caracteres. Cuando se especifica esta bandera, ``^`` coincide al principio " "de la cadena y al comienzo de cada línea dentro de la cadena, inmediatamente " "después de cada nueva línea. De manera similar, el metacarácter ``$`` " "coincide al final de la cadena de caracteres y al final de cada línea " "(inmediatamente antes de cada nueva línea)." #: ../Doc/howto/regex.rst:621 msgid "" "Makes the ``'.'`` special character match any character at all, including a " "newline; without this flag, ``'.'`` will match anything *except* a newline." msgstr "" "Hace que el carácter especial ``'.'`` coincida con cualquier carácter, " "incluida una nueva línea; sin esta bandera, ``'.'`` coincidirá con cualquier " "cosa *except* una nueva línea." #: ../Doc/howto/regex.rst:629 msgid "" "Make ``\\w``, ``\\W``, ``\\b``, ``\\B``, ``\\s`` and ``\\S`` perform ASCII-" "only matching instead of full Unicode matching. This is only meaningful for " "Unicode patterns, and is ignored for byte patterns." msgstr "" "Haga que ``\\w``, ``\\W``, ``\\b``, ``\\B``, ``\\s`` y ``\\S`` realicen una " "coincidencia solo en ASCII en lugar de una coincidencia Unicode completa. " "Esto solo es significativo para los patrones Unicode y se ignora para los " "patrones de bytes." #: ../Doc/howto/regex.rst:638 msgid "" "This flag allows you to write regular expressions that are more readable by " "granting you more flexibility in how you can format them. When this flag " "has been specified, whitespace within the RE string is ignored, except when " "the whitespace is in a character class or preceded by an unescaped " "backslash; this lets you organize and indent the RE more clearly. This flag " "also lets you put comments within a RE that will be ignored by the engine; " "comments are marked by a ``'#'`` that's neither in a character class or " "preceded by an unescaped backslash." msgstr "" "Esta flag le permite escribir expresiones regulares que son más legibles al " "otorgarle más flexibilidad en cómo puede formatearlas. Cuando se ha " "especificado esta flag, los espacios en blanco dentro de la cadena de " "caracteres de la RE se ignoran, excepto cuando el espacio en blanco está en " "una clase de caracteres o está precedido por una barra invertida sin escape; " "esto le permite organizar e indentar la RE más claramente. Esta flag también " "le permite poner comentarios dentro de una RE que serán ignorados por el " "motor (*engine*); los comentarios están marcados con un ``'#'`` que no está " "en una clase de carácter ni está precedido por una barra invertida sin " "escape." #: ../Doc/howto/regex.rst:647 msgid "" "For example, here's a RE that uses :const:`re.VERBOSE`; see how much easier " "it is to read? ::" msgstr "" "Por ejemplo, aquí hay una RE que usa :const:`re.VERBOSE`; ¿Ves lo fácil que " "es leer? ::" #: ../Doc/howto/regex.rst:660 msgid "Without the verbose setting, the RE would look like this::" msgstr "Sin la configuración detallada, la RE se vería así::" #: ../Doc/howto/regex.rst:666 msgid "" "In the above example, Python's automatic concatenation of string literals " "has been used to break up the RE into smaller pieces, but it's still more " "difficult to understand than the version using :const:`re.VERBOSE`." msgstr "" "En el ejemplo anterior, la concatenación automática de cadenas de caracteres " "literales de Python se ha utilizado para dividir la RE en partes más " "pequeñas, pero aún es más difícil de entender que la versión que usa :const:" "`re.VERBOSE`." #: ../Doc/howto/regex.rst:672 msgid "More Pattern Power" msgstr "Más poder de patrones" #: ../Doc/howto/regex.rst:674 msgid "" "So far we've only covered a part of the features of regular expressions. In " "this section, we'll cover some new metacharacters, and how to use groups to " "retrieve portions of the text that was matched." msgstr "" "Hasta ahora solo hemos cubierto una parte de las características de las " "expresiones regulares. En esta sección, cubriremos algunos metacarácteres " "nuevos y cómo usar grupos para recuperar partes del texto que coincidió." #: ../Doc/howto/regex.rst:682 msgid "More Metacharacters" msgstr "Más metacarácteres" #: ../Doc/howto/regex.rst:684 msgid "" "There are some metacharacters that we haven't covered yet. Most of them " "will be covered in this section." msgstr "" "Hay algunos metacarácteres que aún no hemos cubierto. La mayoría de ellos se " "tratarán en esta sección." #: ../Doc/howto/regex.rst:687 msgid "" "Some of the remaining metacharacters to be discussed are :dfn:`zero-width " "assertions`. They don't cause the engine to advance through the string; " "instead, they consume no characters at all, and simply succeed or fail. For " "example, ``\\b`` is an assertion that the current position is located at a " "word boundary; the position isn't changed by the ``\\b`` at all. This means " "that zero-width assertions should never be repeated, because if they match " "once at a given location, they can obviously be matched an infinite number " "of times." msgstr "" "Algunos de los metacarácteres restantes que se discutirán son :dfn:`zero-" "width assertions`. No hacen que el motor avance a través de la cadena de " "caracteres; en cambio, no consumen caracteres en absoluto y simplemente " "tienen éxito o fracasan. Por ejemplo, ``\\b`` es una flag de que la posición " "actual se encuentra en el límite de una palabra; la posición no cambia por " "la ``\\b`` en absoluto. Esto significa que las aserciones de ancho cero " "nunca deben repetirse, porque si coinciden una vez en una ubicación " "determinada, obviamente pueden coincidir un número infinito de veces." #: ../Doc/howto/regex.rst:703 msgid "``|``" msgstr "``|``" #: ../Doc/howto/regex.rst:696 msgid "" "Alternation, or the \"or\" operator. If *A* and *B* are regular " "expressions, ``A|B`` will match any string that matches either *A* or *B*. " "``|`` has very low precedence in order to make it work reasonably when " "you're alternating multi-character strings. ``Crow|Servo`` will match either " "``'Crow'`` or ``'Servo'``, not ``'Cro'``, a ``'w'`` or an ``'S'``, and " "``'ervo'``." msgstr "" "Alternancia, o el operador \"or\". Si *A* y *B* son expresiones regulares, " "``A|B`` coincidirá con cualquier cadena de caracteres que coincida con *A* o " "*B*. ``|`` tiene una precedencia muy baja para que funcione razonablemente " "cuando está alternando cadenas de varios caracteres. ``Crow|Servo`` " "coincidirá con `'Crow'`` o ``'Servo'``, no ``'Cro'``, un ``'w'`` o un " "``'S'``, y ``'ervo'``." #: ../Doc/howto/regex.rst:702 msgid "" "To match a literal ``'|'``, use ``\\|``, or enclose it inside a character " "class, as in ``[|]``." msgstr "" "Para hacer coincidir un literal ``'|'``, use ``\\|``, o enciérrelo dentro de " "una clase de carácter, como en ``[|]``." #: ../Doc/howto/regex.rst:718 msgid "``^``" msgstr "``^``" #: ../Doc/howto/regex.rst:706 msgid "" "Matches at the beginning of lines. Unless the :const:`MULTILINE` flag has " "been set, this will only match at the beginning of the string. In :const:" "`MULTILINE` mode, this also matches immediately after each newline within " "the string." msgstr "" "Coincide con el comienzo de las líneas. A menos que se haya establecido la " "flag :const:`MULTILINE` , esto solo coincidirá al principio de la cadena de " "caracteres. En modo :const:`MULTILINE` , esto también coincide " "inmediatamente después de cada nueva línea dentro de la cadena." #: ../Doc/howto/regex.rst:710 msgid "" "For example, if you wish to match the word ``From`` only at the beginning of " "a line, the RE to use is ``^From``. ::" msgstr "" "Por ejemplo, si desea hacer coincidir la palabra ``From`` solo al principio " "de una línea, la RE que debe usar es ``^From``. ::" #: ../Doc/howto/regex.rst:718 msgid "To match a literal ``'^'``, use ``\\^``." msgstr "Para una coincidencia literal ``'^'``, usar ``\\^``." #: ../Doc/howto/regex.rst:732 msgid "``$``" msgstr "``$``" #: ../Doc/howto/regex.rst:721 msgid "" "Matches at the end of a line, which is defined as either the end of the " "string, or any location followed by a newline character. ::" msgstr "" "Coincide con el final de una línea, que se define como el final de la cadena " "o cualquier ubicación seguida de un carácter de nueva línea. ::" #: ../Doc/howto/regex.rst:731 msgid "" "To match a literal ``'$'``, use ``\\$`` or enclose it inside a character " "class, as in ``[$]``." msgstr "" "Para hacer coincidir un literal ``'$'``, usar ``\\$`` o enciérrelo dentro de " "una clase de carácter, como en ``[$]``." #: ../Doc/howto/regex.rst:738 msgid "``\\A``" msgstr "``\\A``" #: ../Doc/howto/regex.rst:735 msgid "" "Matches only at the start of the string. When not in :const:`MULTILINE` " "mode, ``\\A`` and ``^`` are effectively the same. In :const:`MULTILINE` " "mode, they're different: ``\\A`` still matches only at the beginning of the " "string, but ``^`` may match at any location inside the string that follows a " "newline character." msgstr "" "Coincide solo al comienzo de la cadena de caracteres. Cuando no está en el " "modo :const:`MULTILINE`,``\\A`` y ``^`` son efectivamente lo mismo. En el " "modo :const:`MULTILINE`, son diferentes: ``\\A`` todavía coincide solo al " "principio de la cadena, pero ``^`` puede coincidir en cualquier ubicación " "dentro de la cadena de caracteres que sigue a un carácter de nueva línea." #: ../Doc/howto/regex.rst:741 msgid "``\\Z``" msgstr "``\\Z``" #: ../Doc/howto/regex.rst:741 msgid "Matches only at the end of the string." msgstr "Coincidencias solo al final de la cadena de caracteres." #: ../Doc/howto/regex.rst:776 msgid "``\\b``" msgstr "``\\b``" #: ../Doc/howto/regex.rst:744 msgid "" "Word boundary. This is a zero-width assertion that matches only at the " "beginning or end of a word. A word is defined as a sequence of alphanumeric " "characters, so the end of a word is indicated by whitespace or a non-" "alphanumeric character." msgstr "" "Límite de palabra. Esta es una aserción de ancho cero que coincide solo al " "principio o al final de una palabra. Una palabra se define como una " "secuencia de caracteres alfanuméricos, por lo que el final de una palabra se " "indica mediante un espacio en blanco o un carácter no alfanumérico." #: ../Doc/howto/regex.rst:749 msgid "" "The following example matches ``class`` only when it's a complete word; it " "won't match when it's contained inside another word. ::" msgstr "" "El siguiente ejemplo coincide con ``class`` solo cuando es una palabra " "completa; no coincidirá cuando esté contenido dentro de otra palabra. ::" #: ../Doc/howto/regex.rst:760 msgid "" "There are two subtleties you should remember when using this special " "sequence. First, this is the worst collision between Python's string " "literals and regular expression sequences. In Python's string literals, " "``\\b`` is the backspace character, ASCII value 8. If you're not using raw " "strings, then Python will convert the ``\\b`` to a backspace, and your RE " "won't match as you expect it to. The following example looks the same as our " "previous RE, but omits the ``'r'`` in front of the RE string. ::" msgstr "" "Hay dos sutilezas que debe recordar al usar esta secuencia especial. " "Primero, esta es la peor colisión entre las cadenas literales de caracteres " "de Python y las secuencias de expresiones regulares. En las cadenas de " "caracteres literales de Python, ``\\b`` es el carácter de retroceso " "(*backspace*), valor ASCII 8. Si no está utilizando cadenas de caracteres " "sin procesar, Python convertirá la ``\\b`` en una linea de retroceso, y su " "RE no lo hará coincidir como lo espera. El siguiente ejemplo tiene el mismo " "aspecto que nuestra RE anterior, pero omite la ``'r'`` delante de la cadena " "de caracteres de RE. ::" #: ../Doc/howto/regex.rst:774 msgid "" "Second, inside a character class, where there's no use for this assertion, " "``\\b`` represents the backspace character, for compatibility with Python's " "string literals." msgstr "" "En segundo lugar, dentro de una clase de caracteres, donde no hay uso para " "esta aserción, ``\\b`` representa el carácter de retroceso, por " "compatibilidad con las cadenas de caracteres literales de Python." #: ../Doc/howto/regex.rst:781 msgid "``\\B``" msgstr "``\\B``" #: ../Doc/howto/regex.rst:779 msgid "" "Another zero-width assertion, this is the opposite of ``\\b``, only matching " "when the current position is not at a word boundary." msgstr "" "Otra flag de ancho cero, esto es lo opuesto a ``\\b``, solo coincide cuando " "la posición actual no está en el límite de una palabra." #: ../Doc/howto/regex.rst:784 msgid "Grouping" msgstr "Agrupando" #: ../Doc/howto/regex.rst:786 msgid "" "Frequently you need to obtain more information than just whether the RE " "matched or not. Regular expressions are often used to dissect strings by " "writing a RE divided into several subgroups which match different components " "of interest. For example, an RFC-822 header line is divided into a header " "name and a value, separated by a ``':'``, like this:" msgstr "" "Con frecuencia, necesita obtener más información que solo si la RE coincide " "o no. Las expresiones regulares se utilizan a menudo para diseccionar " "cadenas de caracteres escribiendo una RE dividido en varios subgrupos que " "coinciden con diferentes componentes de interés. Por ejemplo, una línea de " "encabezado RFC-822 se divide en un nombre de encabezado y un valor, " "separados por un ``':'``, así:" #: ../Doc/howto/regex.rst:799 msgid "" "This can be handled by writing a regular expression which matches an entire " "header line, and has one group which matches the header name, and another " "group which matches the header's value." msgstr "" "Esto se puede manejar escribiendo una expresión regular que coincida con una " "línea de encabezado completa y que tenga un grupo que coincida con el nombre " "del encabezado y otro grupo que coincida con el valor del encabezado." #: ../Doc/howto/regex.rst:803 #, fuzzy msgid "" "Groups are marked by the ``'('``, ``')'`` metacharacters. ``'('`` and " "``')'`` have much the same meaning as they do in mathematical expressions; " "they group together the expressions contained inside them, and you can " "repeat the contents of a group with a quantifier, such as ``*``, ``+``, ``?" "``, or ``{m,n}``. For example, ``(ab)*`` will match zero or more " "repetitions of ``ab``. ::" msgstr "" "Los grupos están marcados por los ``'('``, ``')'`` metacarácteres. ``'('`` y " "``')'`` tienen el mismo significado que en las expresiones matemáticas; " "agrupan las expresiones contenidas en ellos, y puedes repetir el contenido " "de un grupo con un calificador repetitivo, como ``*``, ``+``, ``?``, o ``{m," "n}``. Por ejemplo, ``(ab)*`` coincidirá con cero o más repeticiones de " "``ab``. ::" #: ../Doc/howto/regex.rst:814 msgid "" "Groups indicated with ``'('``, ``')'`` also capture the starting and ending " "index of the text that they match; this can be retrieved by passing an " "argument to :meth:`~re.Match.group`, :meth:`~re.Match.start`, :meth:`~re." "Match.end`, and :meth:`~re.Match.span`. Groups are numbered starting with " "0. Group 0 is always present; it's the whole RE, so :ref:`match object " "` methods all have group 0 as their default argument. Later " "we'll see how to express groups that don't capture the span of text that " "they match. ::" msgstr "" "Los grupos indicados con ``'('``, ``')'`` también capturan el índice inicial " "y final del texto que coinciden; esto se puede recuperar pasando un " "argumento a :meth:`~re.Match.group`, :meth:`~re.Match.start`, :meth:`~re." "Match.end`, y :meth:`~re.Match.span`. Los grupos se numeran empezando por 0. " "El grupo 0 siempre está presente; es todo las RE, entonces todos los " "métodos :ref:`match object ` tienen el grupo 0 como argumento " "predeterminado. Más adelante veremos cómo expresar grupos que no capturan el " "espacio de texto que coinciden. ::" #: ../Doc/howto/regex.rst:830 msgid "" "Subgroups are numbered from left to right, from 1 upward. Groups can be " "nested; to determine the number, just count the opening parenthesis " "characters, going from left to right. ::" msgstr "" "Los subgrupos están numerados de izquierda a derecha, de 1 en adelante. Los " "grupos se pueden anidar; para determinar el número, simplemente cuente los " "caracteres del paréntesis de apertura, de izquierda a derecha. ::" #: ../Doc/howto/regex.rst:843 msgid "" ":meth:`~re.Match.group` can be passed multiple group numbers at a time, in " "which case it will return a tuple containing the corresponding values for " "those groups. ::" msgstr "" ":meth:`~re.Match.group` se pueden pasar varios números de grupo a la vez, en " "cuyo caso retornará una tupla que contiene los valores correspondientes para " "esos grupos. ::" #: ../Doc/howto/regex.rst:849 msgid "" "The :meth:`~re.Match.groups` method returns a tuple containing the strings " "for all the subgroups, from 1 up to however many there are. ::" msgstr "" "El método :meth:`~re.Match.groups` retorna una tupla que contiene las " "cadenas de caracteres de todos los subgrupos, desde 1 hasta la cantidad que " "haya. ::" #: ../Doc/howto/regex.rst:855 msgid "" "Backreferences in a pattern allow you to specify that the contents of an " "earlier capturing group must also be found at the current location in the " "string. For example, ``\\1`` will succeed if the exact contents of group 1 " "can be found at the current position, and fails otherwise. Remember that " "Python's string literals also use a backslash followed by numbers to allow " "including arbitrary characters in a string, so be sure to use a raw string " "when incorporating backreferences in a RE." msgstr "" "Las referencias inversas en un patrón le permiten especificar que el " "contenido de un grupo de captura anterior también debe encontrarse en la " "ubicación actual en la cadena. Por ejemplo,``\\1`` tendrá éxito si el " "contenido exacto del grupo 1 se puede encontrar en la posición actual y " "falla en caso contrario. Recuerde que las cadenas de caracteres literales de " "Python también usan una barra invertida seguida de números para permitir la " "inclusión de caracteres arbitrarios en una cadena de caracteres, así que " "asegúrese de usar una cadena de caracteres sin procesar al incorporar " "referencias inversas en una RE." #: ../Doc/howto/regex.rst:863 msgid "For example, the following RE detects doubled words in a string. ::" msgstr "" "Por ejemplo, la siguiente RE detecta palabras duplicadas en una cadena. ::" #: ../Doc/howto/regex.rst:869 msgid "" "Backreferences like this aren't often useful for just searching through a " "string --- there are few text formats which repeat data in this way --- but " "you'll soon find out that they're *very* useful when performing string " "substitutions." msgstr "" "Las referencias inversas como esta no suelen ser útiles para buscar a través " "de una cadena --- hay pocos formatos de texto que repiten datos de esta " "manera --- pero pronto descubrirá que son *muy* útiles al realizar " "sustituciones de cadenas de caracteres." #: ../Doc/howto/regex.rst:875 msgid "Non-capturing and Named Groups" msgstr "Grupos con nombre y sin captura" #: ../Doc/howto/regex.rst:877 msgid "" "Elaborate REs may use many groups, both to capture substrings of interest, " "and to group and structure the RE itself. In complex REs, it becomes " "difficult to keep track of the group numbers. There are two features which " "help with this problem. Both of them use a common syntax for regular " "expression extensions, so we'll look at that first." msgstr "" "Las RE elaboradas pueden utilizar muchos grupos, tanto para capturar " "subcadenas de caracteres de interés como para agrupar y estructurar la " "propia RE. En las RE complejas, resulta difícil realizar un seguimiento de " "los números de los grupos. Hay dos funciones que ayudan con este problema. " "Ambos usan una sintaxis común para las extensiones de expresiones regulares, " "así que veremos eso primero." #: ../Doc/howto/regex.rst:883 msgid "" "Perl 5 is well known for its powerful additions to standard regular " "expressions. For these new features the Perl developers couldn't choose new " "single-keystroke metacharacters or new special sequences beginning with " "``\\`` without making Perl's regular expressions confusingly different from " "standard REs. If they chose ``&`` as a new metacharacter, for example, old " "expressions would be assuming that ``&`` was a regular character and " "wouldn't have escaped it by writing ``\\&`` or ``[&]``." msgstr "" "Perl 5 es bien conocido por sus poderosas adiciones a las expresiones " "regulares estándar. Para estas nuevas características, los desarrolladores " "de Perl no podían elegir nuevos metacarácteres de una sola pulsación de " "tecla o nuevas secuencias especiales que comienzan con ``\\`` sin hacer que " "las expresiones regulares de Perl sean confusamente diferentes de las RE " "estándar. Si eligieran ``&`` como un nuevo metacarácter, por ejemplo, las " "expresiones antiguas supondrían que ``&`` era un carácter regular y no se " "habría escapado escribiendo ``\\&`` o ``[&]``." #: ../Doc/howto/regex.rst:890 msgid "" "The solution chosen by the Perl developers was to use ``(?...)`` as the " "extension syntax. ``?`` immediately after a parenthesis was a syntax error " "because the ``?`` would have nothing to repeat, so this didn't introduce any " "compatibility problems. The characters immediately after the ``?`` " "indicate what extension is being used, so ``(?=foo)`` is one thing (a " "positive lookahead assertion) and ``(?:foo)`` is something else (a non-" "capturing group containing the subexpression ``foo``)." msgstr "" "La solución elegida por los desarrolladores de Perl fue utilizar ``(?...)`` " "como sintaxis de extensión. ``?`` inmediatamente después de un paréntesis " "había un error de sintaxis porque el ``?`` no tendría nada que repetir, por " "lo que esto no introdujo ningún problema de compatibilidad. Los caracteres " "inmediatamente después de ``?`` Indican qué extensión se está utilizando, " "por lo que ``(?=foo)`` es una cosa (una flag de anticipación positiva) y " "``(?:foo)`` es otra cosa (un grupo de no captura que contiene la " "subexpresión ``foo``)." #: ../Doc/howto/regex.rst:898 msgid "" "Python supports several of Perl's extensions and adds an extension syntax to " "Perl's extension syntax. If the first character after the question mark is " "a ``P``, you know that it's an extension that's specific to Python." msgstr "" "Python admite varias de las extensiones de Perl y agrega una sintaxis de " "extensión a la sintaxis de extensión de Perl. Si el primer carácter después " "del signo de interrogación es una ``P``, sabrá que es una extensión " "específica de Python." #: ../Doc/howto/regex.rst:903 msgid "" "Now that we've looked at the general extension syntax, we can return to the " "features that simplify working with groups in complex REs." msgstr "" "Ahora que hemos visto la sintaxis de la extensión general, podemos volver a " "las características que simplifican el trabajo con grupos en RE complejos." #: ../Doc/howto/regex.rst:906 msgid "" "Sometimes you'll want to use a group to denote a part of a regular " "expression, but aren't interested in retrieving the group's contents. You " "can make this fact explicit by using a non-capturing group: ``(?:...)``, " "where you can replace the ``...`` with any other regular expression. ::" msgstr "" "A veces querrá usar un grupo para denotar una parte de una expresión " "regular, pero no está interesado en recuperar el contenido del grupo. Puede " "hacer que este hecho sea explícito utilizando un grupo de no captura: " "``(?:...)``, donde puede reemplazar el ``...`` con cualquier otra expresión " "regular. ::" #: ../Doc/howto/regex.rst:918 msgid "" "Except for the fact that you can't retrieve the contents of what the group " "matched, a non-capturing group behaves exactly the same as a capturing " "group; you can put anything inside it, repeat it with a repetition " "metacharacter such as ``*``, and nest it within other groups (capturing or " "non-capturing). ``(?:...)`` is particularly useful when modifying an " "existing pattern, since you can add new groups without changing how all the " "other groups are numbered. It should be mentioned that there's no " "performance difference in searching between capturing and non-capturing " "groups; neither form is any faster than the other." msgstr "" "Excepto por el hecho de que no puede recuperar el contenido de lo que " "coincide con el grupo, un grupo que no captura se comporta exactamente igual " "que un grupo que captura; puede poner cualquier cosa dentro de él, repetirlo " "con un metacarácter de repetición como ``*`` y anidarlo dentro de otros " "grupos (capturando o no capturando). ``(?:...)`` es particularmente útil " "cuando se modifica un patrón existente, ya que puede agregar nuevos grupos " "sin cambiar cómo se numeran todos los demás grupos. Cabe mencionar que no " "hay diferencia de rendimiento en la búsqueda entre grupos de captura y no " "captura; ninguna forma es más rápida que la otra." #: ../Doc/howto/regex.rst:927 msgid "" "A more significant feature is named groups: instead of referring to them by " "numbers, groups can be referenced by a name." msgstr "" "Una característica más significativa son los grupos nombrados: en lugar de " "referirse a ellos por números, los grupos pueden ser referenciados por un " "nombre." #: ../Doc/howto/regex.rst:930 msgid "" "The syntax for a named group is one of the Python-specific extensions: ``(?" "P...)``. *name* is, obviously, the name of the group. Named groups " "behave exactly like capturing groups, and additionally associate a name with " "a group. The :ref:`match object ` methods that deal with " "capturing groups all accept either integers that refer to the group by " "number or strings that contain the desired group's name. Named groups are " "still given numbers, so you can retrieve information about a group in two " "ways::" msgstr "" "La sintaxis de un grupo con nombre es una de las extensiones específicas de " "Python: ``(?P...)``. *name* es, obviamente, el nombre del grupo. Los " "grupos con nombre se comportan exactamente como los grupos de captura y, " "además, asocian un nombre con un grupo. Los métodos :ref:`match object " "` que tratan con la captura de grupos aceptan enteros que se " "refieren al grupo por número o cadenas de caracteres que contienen el nombre " "del grupo deseado. Los grupos con nombre todavía reciben números, por lo que " "puede recuperar información sobre un grupo de dos maneras:" #: ../Doc/howto/regex.rst:945 msgid "" "Additionally, you can retrieve named groups as a dictionary with :meth:`~re." "Match.groupdict`::" msgstr "" "Además, puede recuperar grupos nombrados como un diccionario con :meth:`~re." "Match.groupdict`::" #: ../Doc/howto/regex.rst:952 #, fuzzy msgid "" "Named groups are handy because they let you use easily remembered names, " "instead of having to remember numbers. Here's an example RE from the :mod:" "`imaplib` module::" msgstr "" "Los grupos con nombre son útiles porque le permiten usar nombres fáciles de " "recordar, en lugar de tener que recordar números. Aquí hay un ejemplo de RE " "del módulo :mod:`imaplib`::" #: ../Doc/howto/regex.rst:963 msgid "" "It's obviously much easier to retrieve ``m.group('zonem')``, instead of " "having to remember to retrieve group 9." msgstr "" "Obviamente, es mucho más fácil recuperar ``m.group('zonem')``, en lugar de " "tener que recordar recuperar el grupo 9." #: ../Doc/howto/regex.rst:966 msgid "" "The syntax for backreferences in an expression such as ``(...)\\1`` refers " "to the number of the group. There's naturally a variant that uses the group " "name instead of the number. This is another Python extension: ``(?P=name)`` " "indicates that the contents of the group called *name* should again be " "matched at the current point. The regular expression for finding doubled " "words, ``\\b(\\w+)\\s+\\1\\b`` can also be written as ``\\b(?" "P\\w+)\\s+(?P=word)\\b``::" msgstr "" "La sintaxis de las referencias inversas en una expresión como ``(...)\\1`` " "se refiere al número del grupo. Naturalmente, existe una variante que usa el " "nombre del grupo en lugar del número. Esta es otra extensión de Python: ``(?" "P=name)`` indica que el contenido del grupo llamado *name* debe coincidir " "nuevamente en el punto actual. La expresión regular para encontrar palabras " "duplicadas, ``\\b(\\w+)\\s+\\1\\b`` también se puede escribir como ``\\b(?" "P\\w+)\\s+(?P=word)\\b``::" #: ../Doc/howto/regex.rst:979 msgid "Lookahead Assertions" msgstr "Aserciones Anticipadas" #: ../Doc/howto/regex.rst:981 msgid "" "Another zero-width assertion is the lookahead assertion. Lookahead " "assertions are available in both positive and negative form, and look like " "this:" msgstr "" "Otra aserción de ancho cero es la aserción de anticipación. Las afirmaciones " "anticipadas están disponibles tanto en forma positiva como negativa, y " "tienen este aspecto:" #: ../Doc/howto/regex.rst:989 msgid "``(?=...)``" msgstr "``(?=...)``" #: ../Doc/howto/regex.rst:985 msgid "" "Positive lookahead assertion. This succeeds if the contained regular " "expression, represented here by ``...``, successfully matches at the current " "location, and fails otherwise. But, once the contained expression has been " "tried, the matching engine doesn't advance at all; the rest of the pattern " "is tried right where the assertion started." msgstr "" "Aserción de anticipación positiva. Esto tiene éxito si la expresión regular " "contenida, representada aquí por ``...``, coincide con éxito en la ubicación " "actual y falla en caso contrario. Pero, una vez que se ha probado la " "expresión contenida, el motor de comparación no avanza en absoluto; el resto " "del patrón se intenta justo donde comenzó la aserción." #: ../Doc/howto/regex.rst:994 msgid "``(?!...)``" msgstr "``(?!...)``" #: ../Doc/howto/regex.rst:992 msgid "" "Negative lookahead assertion. This is the opposite of the positive " "assertion; it succeeds if the contained expression *doesn't* match at the " "current position in the string." msgstr "" "Aserción de anticipación negativa. Esto es lo opuesto a la flag positiva; " "tiene éxito si la expresión contenida *no* coincide con la posición actual " "en la cadena." #: ../Doc/howto/regex.rst:996 msgid "" "To make this concrete, let's look at a case where a lookahead is useful. " "Consider a simple pattern to match a filename and split it apart into a base " "name and an extension, separated by a ``.``. For example, in ``news.rc``, " "``news`` is the base name, and ``rc`` is the filename's extension." msgstr "" "Para que esto sea concreto, veamos un caso en el que una búsqueda anticipada " "es útil. Considere un patrón simple para hacer coincidir un nombre de " "archivo y dividirlo en un nombre base y una extensión, separados por un ``." "``. Por ejemplo, en ``news.rc``, ``news`` es el nombre base y ``rc`` es la " "extensión del nombre del archivo." #: ../Doc/howto/regex.rst:1001 msgid "The pattern to match this is quite simple:" msgstr "El patrón para que coincida con esto es bastante simple:" #: ../Doc/howto/regex.rst:1003 msgid "``.*[.].*$``" msgstr "``.*[.].*$``" #: ../Doc/howto/regex.rst:1005 msgid "" "Notice that the ``.`` needs to be treated specially because it's a " "metacharacter, so it's inside a character class to only match that specific " "character. Also notice the trailing ``$``; this is added to ensure that all " "the rest of the string must be included in the extension. This regular " "expression matches ``foo.bar`` and ``autoexec.bat`` and ``sendmail.cf`` and " "``printers.conf``." msgstr "" "Tenga en cuenta que el ``.`` Debe tratarse especialmente porque es un " "metacarácter, por lo que está dentro de una clase de carácter para coincidir " "solo con ese carácter específico. También observe el final ``$``; esto se " "agrega para garantizar que todo el resto de la cadena deba incluirse en la " "extensión. Esta expresión regular coincide con ``foo.bar`` y ``autoexec." "bat`` y ``sendmail.cf`` y ``printers.conf``." #: ../Doc/howto/regex.rst:1012 msgid "" "Now, consider complicating the problem a bit; what if you want to match " "filenames where the extension is not ``bat``? Some incorrect attempts:" msgstr "" "Ahora, considere complicar un poco el problema; ¿Qué sucede si desea hacer " "coincidir los nombres de archivo donde la extensión no es ``bat``? Algunos " "intentos incorrectos:" #: ../Doc/howto/regex.rst:1015 msgid "" "``.*[.][^b].*$`` The first attempt above tries to exclude ``bat`` by " "requiring that the first character of the extension is not a ``b``. This is " "wrong, because the pattern also doesn't match ``foo.bar``." msgstr "" "``.*[.][^b].*$`` El primer intento anterior intenta excluir ``bat`` " "requiriendo que el primer carácter de la extensión no sea una ``b``. Esto " "está mal, porque el patrón tampoco coincide ``foo.bar``." #: ../Doc/howto/regex.rst:1019 msgid "``.*[.]([^b]..|.[^a].|..[^t])$``" msgstr "``.*[.]([^b]..|.[^a].|..[^t])$``" #: ../Doc/howto/regex.rst:1021 msgid "" "The expression gets messier when you try to patch up the first solution by " "requiring one of the following cases to match: the first character of the " "extension isn't ``b``; the second character isn't ``a``; or the third " "character isn't ``t``. This accepts ``foo.bar`` and rejects ``autoexec." "bat``, but it requires a three-letter extension and won't accept a filename " "with a two-letter extension such as ``sendmail.cf``. We'll complicate the " "pattern again in an effort to fix it." msgstr "" "La expresión se vuelve más desordenada cuando intenta parchear la primera " "solución requiriendo que coincida uno de los siguientes casos: el primer " "carácter de la extensión no es ``b``; el segundo carácter no es ``a``; o el " "tercer carácter no es ``t``. Esto acepta ``foo.bar`` y rechaza ``autoexec." "bat``, pero requiere una extensión de tres letras y no acepta un nombre de " "archivo con una extensión de dos letras como ``sendmail.cf``. Complicaremos " "el patrón nuevamente en un esfuerzo por arreglarlo." #: ../Doc/howto/regex.rst:1029 msgid "``.*[.]([^b].?.?|.[^a]?.?|..?[^t]?)$``" msgstr "``.*[.]([^b].?.?|.[^a]?.?|..?[^t]?)$``" #: ../Doc/howto/regex.rst:1031 msgid "" "In the third attempt, the second and third letters are all made optional in " "order to allow matching extensions shorter than three characters, such as " "``sendmail.cf``." msgstr "" "En el tercer intento, la segunda y tercera letras se hacen opcionales para " "permitir extensiones coincidentes de menos de tres caracteres, como " "``sendmail.cf``." #: ../Doc/howto/regex.rst:1035 msgid "" "The pattern's getting really complicated now, which makes it hard to read " "and understand. Worse, if the problem changes and you want to exclude both " "``bat`` and ``exe`` as extensions, the pattern would get even more " "complicated and confusing." msgstr "" "El patrón se está volviendo realmente complicado ahora, lo que dificulta su " "lectura y comprensión. Peor aún, si el problema cambia y desea excluir tanto " "``bat`` y ``exe`` como extensiones, el patrón se volvería aún más complicado " "y confuso." #: ../Doc/howto/regex.rst:1040 msgid "A negative lookahead cuts through all this confusion:" msgstr "Una mirada anticipada negativa atraviesa toda esta confusión:" #: ../Doc/howto/regex.rst:1042 msgid "" "``.*[.](?!bat$)[^.]*$`` The negative lookahead means: if the expression " "``bat`` doesn't match at this point, try the rest of the pattern; if " "``bat$`` does match, the whole pattern will fail. The trailing ``$`` is " "required to ensure that something like ``sample.batch``, where the extension " "only starts with ``bat``, will be allowed. The ``[^.]*`` makes sure that " "the pattern works when there are multiple dots in the filename." msgstr "" "``.*[.](?!bat$)[^.]*$`` La búsqueda anticipada negativa significa: si la " "expresión ``bat`` no coincide en este punto, pruebe el resto del patrón; si " "``bat$`` coincide, todo el patrón fallará. El ``$`` final es necesario para " "garantizar que se permita algo como ``sample.batch``, donde la extensión " "solo comienza con ``bat``. El ``[^.]*`` asegura que el patrón funcione " "cuando hay varios puntos en el nombre del archivo." #: ../Doc/howto/regex.rst:1049 msgid "" "Excluding another filename extension is now easy; simply add it as an " "alternative inside the assertion. The following pattern excludes filenames " "that end in either ``bat`` or ``exe``:" msgstr "" "Ahora es fácil excluir otra extensión de nombre de archivo; simplemente " "agréguelo como una alternativa dentro de la aserción. El siguiente patrón " "excluye los nombres de archivo que terminan en ``bat`` o ``exe``:" #: ../Doc/howto/regex.rst:1053 msgid "``.*[.](?!bat$|exe$)[^.]*$``" msgstr "``.*[.](?!bat$|exe$)[^.]*$``" #: ../Doc/howto/regex.rst:1057 msgid "Modifying Strings" msgstr "Modificando cadenas de caracteres" #: ../Doc/howto/regex.rst:1059 msgid "" "Up to this point, we've simply performed searches against a static string. " "Regular expressions are also commonly used to modify strings in various " "ways, using the following pattern methods:" msgstr "" "Hasta este punto, simplemente hemos realizado búsquedas en una cadena de " "caracteres estática. Las expresiones regulares también se utilizan " "comúnmente para modificar cadenas de varias formas, utilizando los " "siguientes métodos de patrón:" #: ../Doc/howto/regex.rst:1066 msgid "``split()``" msgstr "``split()``" #: ../Doc/howto/regex.rst:1066 msgid "Split the string into a list, splitting it wherever the RE matches" msgstr "" "Divida la cadena de caracteres en una lista, dividiéndola donde coincida la " "RE" #: ../Doc/howto/regex.rst:1069 msgid "``sub()``" msgstr "``sub()``" #: ../Doc/howto/regex.rst:1069 msgid "" "Find all substrings where the RE matches, and replace them with a different " "string" msgstr "" "Encuentra todas las subcadenas de caracteres donde coincida la RE y las " "reemplaza con una cadena de caracteres diferente" #: ../Doc/howto/regex.rst:1072 msgid "``subn()``" msgstr "``subn()``" #: ../Doc/howto/regex.rst:1072 msgid "" "Does the same thing as :meth:`!sub`, but returns the new string and the " "number of replacements" msgstr "" "Hace lo mismo que :meth:`!sub`, pero retorna la nueva cadena de caracteres y " "el número de reemplazos" #: ../Doc/howto/regex.rst:1079 msgid "Splitting Strings" msgstr "Separando cadenas de caracteres" #: ../Doc/howto/regex.rst:1081 msgid "" "The :meth:`~re.Pattern.split` method of a pattern splits a string apart " "wherever the RE matches, returning a list of the pieces. It's similar to " "the :meth:`~str.split` method of strings but provides much more generality " "in the delimiters that you can split by; string :meth:`!split` only supports " "splitting by whitespace or by a fixed string. As you'd expect, there's a " "module-level :func:`re.split` function, too." msgstr "" "El método :meth:`~re.Pattern.split` de un patrón que divide una cadena de " "caracteres donde la RE coincide, retornando una lista de las piezas. Es " "similar al método de cadenas de caracteres :meth:`~str.split` pero " "proporciona mucha más generalidad en los delimitadores por los que puede " "dividir; cadena de caracteres :meth:`!split` solo admite la división por " "espacios en blanco o por una cadena fija. Como era de esperar, también hay " "una función a nivel de módulo :func:`re.split`." #: ../Doc/howto/regex.rst:1092 msgid "" "Split *string* by the matches of the regular expression. If capturing " "parentheses are used in the RE, then their contents will also be returned as " "part of the resulting list. If *maxsplit* is nonzero, at most *maxsplit* " "splits are performed." msgstr "" "Dividir *string* por las coincidencias de la expresión regular. Si se " "utilizan paréntesis de captura en la RE, su contenido también se retornará " "como parte de la lista resultante. Si *maxsplit* es distinto de cero, se " "realizan como máximo divisiones *maxsplit* ." #: ../Doc/howto/regex.rst:1097 msgid "" "You can limit the number of splits made, by passing a value for *maxsplit*. " "When *maxsplit* is nonzero, at most *maxsplit* splits will be made, and the " "remainder of the string is returned as the final element of the list. In " "the following example, the delimiter is any sequence of non-alphanumeric " "characters. ::" msgstr "" "Puede limitar el número de divisiones realizadas, pasando un valor para " "*maxsplit*. Cuando *maxsplit* es distinto de cero, se realizarán como máximo " "*maxsplit* divisiones, y el resto de la cadena de caracteres se retorna como " "el elemento final de la lista. En el siguiente ejemplo, el delimitador es " "cualquier secuencia de caracteres no alfanuméricos. ::" #: ../Doc/howto/regex.rst:1109 msgid "" "Sometimes you're not only interested in what the text between delimiters is, " "but also need to know what the delimiter was. If capturing parentheses are " "used in the RE, then their values are also returned as part of the list. " "Compare the following calls::" msgstr "" "A veces, no solo le interesa cuál es el texto entre delimitadores, sino que " "también necesita saber cuál era el delimitador. Si se utilizan paréntesis de " "captura en la RE, sus valores también se retornan como parte de la lista. " "Compare las siguientes llamadas:" #: ../Doc/howto/regex.rst:1121 msgid "" "The module-level function :func:`re.split` adds the RE to be used as the " "first argument, but is otherwise the same. ::" msgstr "" "La función de nivel de módulo :func:`re.split` agrega la RE que se usará " "como primer argumento, pero por lo demás es el mismo. ::" #: ../Doc/howto/regex.rst:1133 msgid "Search and Replace" msgstr "Búsqueda y Remplazo" #: ../Doc/howto/regex.rst:1135 msgid "" "Another common task is to find all the matches for a pattern, and replace " "them with a different string. The :meth:`~re.Pattern.sub` method takes a " "replacement value, which can be either a string or a function, and the " "string to be processed." msgstr "" "Otra tarea común es encontrar todas las coincidencias para un patrón y " "reemplazarlas con una cadena de caracteres diferente. El método :meth:`~re." "Pattern.sub` toma un valor de reemplazo, que puede ser una cadena de " "caracteres o una función, y la cadena de caracteres a procesar." #: ../Doc/howto/regex.rst:1142 msgid "" "Returns the string obtained by replacing the leftmost non-overlapping " "occurrences of the RE in *string* by the replacement *replacement*. If the " "pattern isn't found, *string* is returned unchanged." msgstr "" "Retorna la cadena de caracteres obtenida al reemplazar las apariciones no " "superpuestas del extremo izquierdo de la RE en *string* por el remplazo " "*replacement*. Si no se encuentra el patrón, el *string* se retorna sin " "cambios." #: ../Doc/howto/regex.rst:1146 msgid "" "The optional argument *count* is the maximum number of pattern occurrences " "to be replaced; *count* must be a non-negative integer. The default value " "of 0 means to replace all occurrences." msgstr "" "El argumento opcional *count* es el número máximo de ocurrencias de patrones " "que se reemplazarán; *count* debe ser un número entero no negativo. El valor " "predeterminado de 0 significa reemplazar todas las ocurrencias." #: ../Doc/howto/regex.rst:1150 msgid "" "Here's a simple example of using the :meth:`~re.Pattern.sub` method. It " "replaces colour names with the word ``colour``::" msgstr "" "Aquí hay un ejemplo simple del uso del método :meth:`~re.Pattern.sub`. " "Reemplaza los nombres de los colores con la palabra ``colour``::" #: ../Doc/howto/regex.rst:1159 msgid "" "The :meth:`~re.Pattern.subn` method does the same work, but returns a 2-" "tuple containing the new string value and the number of replacements that " "were performed::" msgstr "" "El método :meth:`~re.Pattern.subn` hace el mismo trabajo, pero retorna una " "tupla de 2 que contiene el nuevo valor de cadena de caracteres y el número " "de reemplazos que se realizaron::" #: ../Doc/howto/regex.rst:1168 msgid "" "Empty matches are replaced only when they're not adjacent to a previous " "empty match. ::" msgstr "" "Las coincidencias vacías se reemplazan solo cuando no son adyacentes a una " "coincidencia vacía anterior. ::" #: ../Doc/howto/regex.rst:1175 msgid "" "If *replacement* is a string, any backslash escapes in it are processed. " "That is, ``\\n`` is converted to a single newline character, ``\\r`` is " "converted to a carriage return, and so forth. Unknown escapes such as " "``\\&`` are left alone. Backreferences, such as ``\\6``, are replaced with " "the substring matched by the corresponding group in the RE. This lets you " "incorporate portions of the original text in the resulting replacement " "string." msgstr "" "Si *replacement* es una cadena, se procesan los escapes de barra invertida " "que contenga. Es decir, ``\\n`` se convierte en un solo carácter de nueva " "línea, ``\\r`` se convierte en una REtorno de carro, y así sucesivamente. " "Los escapes desconocidos como ``\\&`` se dejan en paz. Las referencias " "inversas, como ``\\6``, se reemplazan con la subcadena de caracteres que " "coincide con el grupo correspondiente a la RE. Esto le permite incorporar " "partes del texto original en la cadena de reemplazo resultante." #: ../Doc/howto/regex.rst:1182 msgid "" "This example matches the word ``section`` followed by a string enclosed in " "``{``, ``}``, and changes ``section`` to ``subsection``::" msgstr "" "Este ejemplo hace coincidir la palabra ``section`` seguida de una cadena " "encerrada entre ``{``, ``}``, y cambia ``section`` a ``subsection``::" #: ../Doc/howto/regex.rst:1189 msgid "" "There's also a syntax for referring to named groups as defined by the ``(?" "P...)`` syntax. ``\\g`` will use the substring matched by the " "group named ``name``, and ``\\g`` uses the corresponding group " "number. ``\\g<2>`` is therefore equivalent to ``\\2``, but isn't ambiguous " "in a replacement string such as ``\\g<2>0``. (``\\20`` would be interpreted " "as a reference to group 20, not a reference to group 2 followed by the " "literal character ``'0'``.) The following substitutions are all equivalent, " "but use all three variations of the replacement string. ::" msgstr "" "También hay una sintaxis para hacer referencia a grupos con nombre según lo " "definido por la sintaxis ``(?P…)``syntax. ``\\g`` usará la " "subcadena de caracteres que coincide con el grupo llamado ``name``, y " "``\\g`` usa el número de grupo correspondiente. ``\\g<2>`` es " "equivalente a ``\\2``, pero no es ambiguo en una cadena de reemplazo como " "``\\g<2>0``. (``\\20`` se interpretaría como una referencia al grupo 20, no " "como una referencia al grupo 2 seguido del carácter literal ``'0'``.) Las " "siguientes sustituciones son todas equivalentes, pero use las tres " "variaciones de la cadena de reemplazo. ::" #: ../Doc/howto/regex.rst:1206 msgid "" "*replacement* can also be a function, which gives you even more control. If " "*replacement* is a function, the function is called for every non-" "overlapping occurrence of *pattern*. On each call, the function is passed " "a :ref:`match object ` argument for the match and can use " "this information to compute the desired replacement string and return it." msgstr "" "*replacement* también puede ser una función, lo que le brinda aún más " "control. Si *replacement* es una función, la función se llama para cada " "ocurrencia no superpuesta de *pattern*. En cada llamada, a la función se le " "pasa un argumento :ref:`match object ` para la coincidencia y " "puede usar esta información para calcular la cadena de reemplazo deseada y " "retornarla." #: ../Doc/howto/regex.rst:1212 msgid "" "In the following example, the replacement function translates decimals into " "hexadecimal::" msgstr "" "En el siguiente ejemplo, la función de reemplazo traduce decimales a " "hexadecimales::" #: ../Doc/howto/regex.rst:1224 msgid "" "When using the module-level :func:`re.sub` function, the pattern is passed " "as the first argument. The pattern may be provided as an object or as a " "string; if you need to specify regular expression flags, you must either use " "a pattern object as the first parameter, or use embedded modifiers in the " "pattern string, e.g. ``sub(\"(?i)b+\", \"x\", \"bbbb BBBB\")`` returns ``'x " "x'``." msgstr "" "Cuando se usa la función *module-level* :func:`re.sub`, el patrón se pasa " "como primer argumento. El patrón puede proporcionarse como un objeto o como " "una cuerda; Si necesita especificar marcas de expresión regular, debe usar " "un objeto de patrón como primer parámetro o usar modificadores incrustados " "en la cadena de patrón, por ejemplo ``sub(\"(?i)b+\", \"x\", \"bbbb " "BBBB\")`` retorna ``'x x'``." #: ../Doc/howto/regex.rst:1232 msgid "Common Problems" msgstr "Problemas comunes" #: ../Doc/howto/regex.rst:1234 msgid "" "Regular expressions are a powerful tool for some applications, but in some " "ways their behaviour isn't intuitive and at times they don't behave the way " "you may expect them to. This section will point out some of the most common " "pitfalls." msgstr "" "Las expresiones regulares son una herramienta poderosa para algunas " "aplicaciones, pero de alguna manera su comportamiento no es intuitivo y, a " "veces, no se comportan de la forma esperada. Esta sección señalará algunos " "de los errores más comunes." #: ../Doc/howto/regex.rst:1240 msgid "Use String Methods" msgstr "Uso de métodos de cadenas de caracteres" #: ../Doc/howto/regex.rst:1242 msgid "" "Sometimes using the :mod:`re` module is a mistake. If you're matching a " "fixed string, or a single character class, and you're not using any :mod:" "`re` features such as the :const:`~re.IGNORECASE` flag, then the full power " "of regular expressions may not be required. Strings have several methods for " "performing operations with fixed strings and they're usually much faster, " "because the implementation is a single small C loop that's been optimized " "for the purpose, instead of the large, more generalized regular expression " "engine." msgstr "" "A veces, usar el módulo :mod:`re` es un error. Si está haciendo coincidir " "una cadena de caracteres fija, o una clase de un solo caracter, y no está " "usando ninguna característica :mod:`re` como la marca :const:`~re." "IGNORECASE`, entonces todo el poder de las expresiones regulares puede que " "no sea necesario. Las cadenas tienen varios métodos para realizar " "operaciones con cadenas fijas y, por lo general, son mucho más rápidas, " "porque la implementación es un único bucle C pequeño que se ha optimizado " "para este propósito, en lugar del motor de expresión regular más grande y " "generalizado." #: ../Doc/howto/regex.rst:1250 msgid "" "One example might be replacing a single fixed string with another one; for " "example, you might replace ``word`` with ``deed``. :func:`re.sub` seems " "like the function to use for this, but consider the :meth:`~str.replace` " "method. Note that :meth:`!replace` will also replace ``word`` inside words, " "turning ``swordfish`` into ``sdeedfish``, but the naive RE ``word`` would " "have done that, too. (To avoid performing the substitution on parts of " "words, the pattern would have to be ``\\bword\\b``, in order to require that " "``word`` have a word boundary on either side. This takes the job beyond :" "meth:`!replace`'s abilities.)" msgstr "" "Un ejemplo podría ser reemplazar una sola cadena fija por otra; por ejemplo, " "puede reemplazar ``word`` por ``deed``. :func:`re.sub` parece la función a " "utilizar para esto, pero considere el método :meth:`~str.replace`. Tenga en " "cuenta que :meth:`!replace` también reemplazará ``word`` dentro de las " "palabras, convirtiendo ``swordfish`` en ``sdeedfish``, pero la RE naíf " "``word`` también lo habría hecho. (Para evitar realizar la sustitución en " "partes de palabras, el patrón tendría que ser ``\\bword\\b``, para requerir " "que ``word`` tenga un límite de palabra en cada lado. Esto lleva el trabajo " "más allá de las habilidades de :meth:`!replace`.)" #: ../Doc/howto/regex.rst:1259 msgid "" "Another common task is deleting every occurrence of a single character from " "a string or replacing it with another single character. You might do this " "with something like ``re.sub('\\n', ' ', S)``, but :meth:`~str.translate` is " "capable of doing both tasks and will be faster than any regular expression " "operation can be." msgstr "" "Otra tarea común es eliminar cada aparición de un solo carácter de una " "cadena o reemplazarlo con otro solo carácter. Puede hacer esto con algo como " "``re.sub('\\n', ' ', S)``, pero :meth:`~str.translate` es capaz de realizar " "ambas tareas y será más rápido que cualquier expresión regular la operación " "puede ser." #: ../Doc/howto/regex.rst:1265 msgid "" "In short, before turning to the :mod:`re` module, consider whether your " "problem can be solved with a faster and simpler string method." msgstr "" "En resumen, antes de pasar al módulo :mod:`re`, considere si su problema " "puede resolverse con un método de cadena de caracteres más rápido y simple." #: ../Doc/howto/regex.rst:1270 msgid "match() versus search()" msgstr "*match() versus search()*" #: ../Doc/howto/regex.rst:1272 msgid "" "The :func:`~re.match` function only checks if the RE matches at the " "beginning of the string while :func:`~re.search` will scan forward through " "the string for a match. It's important to keep this distinction in mind. " "Remember, :func:`!match` will only report a successful match which will " "start at 0; if the match wouldn't start at zero, :func:`!match` will *not* " "report it. ::" msgstr "" "La función :func:`~re.match` solo verifica si la RE coincide con el comienzo " "de la cadena de caracteres, mientras que :func:`~re.search` buscará una " "coincidencia en la cadena de caracteres. Es importante tener en cuenta esta " "distinción. Recuerde :func:`!match` solo informará una coincidencia exitosa " "que comenzará en 0; si la coincidencia no comienza en cero, :func:`!match` " "*no* lo informará. ::" #: ../Doc/howto/regex.rst:1283 msgid "" "On the other hand, :func:`~re.search` will scan forward through the string, " "reporting the first match it finds. ::" msgstr "" "Por otro lado, :func:`~re.search` escaneará hacia adelante a través de la " "cadena de caracteres, informando la primera coincidencia que encuentre. ::" #: ../Doc/howto/regex.rst:1291 msgid "" "Sometimes you'll be tempted to keep using :func:`re.match`, and just add ``." "*`` to the front of your RE. Resist this temptation and use :func:`re." "search` instead. The regular expression compiler does some analysis of REs " "in order to speed up the process of looking for a match. One such analysis " "figures out what the first character of a match must be; for example, a " "pattern starting with ``Crow`` must match starting with a ``'C'``. The " "analysis lets the engine quickly scan through the string looking for the " "starting character, only trying the full match if a ``'C'`` is found." msgstr "" "A veces, tendrá la tentación de seguir usando :func:`re.match`, y " "simplemente agregar ``.*`` al frente de su RE. Resista esta tentación y use :" "func:`re.search` en su lugar. El compilador de expresiones regulares realiza " "un análisis de las RE para acelerar el proceso de búsqueda de coincidencias. " "Uno de esos análisis determina cuál debe ser el primer carácter de una " "coincidencia; por ejemplo, un patrón que comienza con ``Crow`` debe " "coincidir con una ``'C'``.El análisis permite que el motor escanee " "rápidamente a través de la cadena en busca del carácter inicial, solo " "probando la coincidencia completa si se encuentra una ``'C'``." #: ../Doc/howto/regex.rst:1300 msgid "" "Adding ``.*`` defeats this optimization, requiring scanning to the end of " "the string and then backtracking to find a match for the rest of the RE. " "Use :func:`re.search` instead." msgstr "" "Agregar ``.*`` anula esta optimización, lo que requiere escanear hasta el " "final de la cadena y luego retroceder para encontrar una coincidencia para " "el resto de la RE. Utilice :func:`re.search` en su lugar." #: ../Doc/howto/regex.rst:1306 msgid "Greedy versus Non-Greedy" msgstr "Codiciosa versus no codiciosa (*Greedy versus Non-Greedy*)" #: ../Doc/howto/regex.rst:1308 msgid "" "When repeating a regular expression, as in ``a*``, the resulting action is " "to consume as much of the pattern as possible. This fact often bites you " "when you're trying to match a pair of balanced delimiters, such as the angle " "brackets surrounding an HTML tag. The naive pattern for matching a single " "HTML tag doesn't work because of the greedy nature of ``.*``. ::" msgstr "" "Al repetir una expresión regular, como en ``a*``, la acción resultante es " "consumir la mayor cantidad posible del patrón. Este hecho suele molestarle " "cuando intenta hacer coincidir un par de delimitadores equilibrados, como " "los corchetes angulares que rodean una etiqueta HTML. El patrón ingenuo para " "hacer coincidir una sola etiqueta HTML no funciona debido a la naturaleza " "codiciosa de ``.*``. ::" #: ../Doc/howto/regex.rst:1322 msgid "" "The RE matches the ``'<'`` in ``''``, and the ``.*`` consumes the rest " "of the string. There's still more left in the RE, though, and the ``>`` " "can't match at the end of the string, so the regular expression engine has " "to backtrack character by character until it finds a match for the ``>``. " "The final match extends from the ``'<'`` in ``''`` to the ``'>'`` in " "``''``, which isn't what you want." msgstr "" "La RE coincide con el ``'<'`` en ``''``, y el ``.*`` consume el resto " "de la cadena de caracteres. Sin embargo, aún queda más en la RE y el ``>`` " "no puede coincidir al final de la cadena de caracteres, por lo que el motor " "de la expresión regular tiene que retroceder carácter por carácter hasta que " "encuentre una coincidencia para el ``>``. La coincidencia final se extiende " "desde el `'<'`` en ``''`` al ``'>'`` en ``''``, que no es lo " "que queremos." #: ../Doc/howto/regex.rst:1329 #, fuzzy msgid "" "In this case, the solution is to use the non-greedy quantifiers ``*?``, ``+?" "``, ``??``, or ``{m,n}?``, which match as *little* text as possible. In the " "above example, the ``'>'`` is tried immediately after the first ``'<'`` " "matches, and when it fails, the engine advances a character at a time, " "retrying the ``'>'`` at every step. This produces just the right result::" msgstr "" "En este caso, la solución es utilizar los calificadores no codiciosos ``*?" "``, ``+?``, ``??``, o ``{m,n}?``, Que coinciden como *poco* texto como sea " "posible. En el ejemplo anterior, el ``'>'`` se prueba inmediatamente después " "de las primeras coincidencias ``'<'``, y cuando falla, el motor avanza un " "carácter a la vez, volviendo a intentar el ``'>'`` en cada paso. Esto " "produce el resultado correcto:" #: ../Doc/howto/regex.rst:1338 msgid "" "(Note that parsing HTML or XML with regular expressions is painful. Quick-" "and-dirty patterns will handle common cases, but HTML and XML have special " "cases that will break the obvious regular expression; by the time you've " "written a regular expression that handles all of the possible cases, the " "patterns will be *very* complicated. Use an HTML or XML parser module for " "such tasks.)" msgstr "" "(Tenga en cuenta que analizar HTML o XML con expresiones regulares es " "doloroso. Los patrones rápidos y sucios manejarán casos comunes, pero HTML y " "XML tienen casos especiales que romperán la expresión regular obvia; para " "cuando haya escrito una expresión regular que maneja todos los casos " "posibles, los patrones serán *muy* complicados. Utilice un módulo analizador " "HTML o XML para tales tareas.)" #: ../Doc/howto/regex.rst:1346 msgid "Using re.VERBOSE" msgstr "Usando re.VERBOSE" #: ../Doc/howto/regex.rst:1348 msgid "" "By now you've probably noticed that regular expressions are a very compact " "notation, but they're not terribly readable. REs of moderate complexity can " "become lengthy collections of backslashes, parentheses, and metacharacters, " "making them difficult to read and understand." msgstr "" "Probablemente ya haya notado que las expresiones regulares son una notación " "muy compacta, pero no son muy legibles. Las RE de complejidad moderada " "pueden convertirse en largas colecciones de barras invertidas, paréntesis y " "metacarácteres, lo que dificulta su lectura y comprensión." #: ../Doc/howto/regex.rst:1353 msgid "" "For such REs, specifying the :const:`re.VERBOSE` flag when compiling the " "regular expression can be helpful, because it allows you to format the " "regular expression more clearly." msgstr "" "Para tales RE, especificar el flag :const:`re.VERBOSE` al compilar la " "expresión regular puede ser útil, porque le permite formatear la expresión " "regular con mayor claridad." #: ../Doc/howto/regex.rst:1357 msgid "" "The ``re.VERBOSE`` flag has several effects. Whitespace in the regular " "expression that *isn't* inside a character class is ignored. This means " "that an expression such as ``dog | cat`` is equivalent to the less readable " "``dog|cat``, but ``[a b]`` will still match the characters ``'a'``, ``'b'``, " "or a space. In addition, you can also put comments inside a RE; comments " "extend from a ``#`` character to the next newline. When used with triple-" "quoted strings, this enables REs to be formatted more neatly::" msgstr "" "La flag ``re.VERBOSE`` tiene varios efectos. Los espacios en blanco en la " "expresión regular que *no están* dentro de una clase de caracteres se " "ignoran. Esto significa que una expresión como ``dog | cat`` es equivalente " "al menos legible ``dog | cat``, pero ``[a b]`` seguirá coincidiendo con los " "caracteres ``'a'``, ``'b'`` o un espacio. Además, también puede poner " "comentarios dentro de una RE; los comentarios se extienden desde un carácter " "``#`` hasta la siguiente línea nueva. Cuando se usa con cadenas entre " "comillas triples, esto permite que las REs sean formateados de manera más " "ordenada:" #: ../Doc/howto/regex.rst:1374 msgid "This is far more readable than::" msgstr "Esto es mas legible que::" #: ../Doc/howto/regex.rst:1380 msgid "Feedback" msgstr "Feedback" #: ../Doc/howto/regex.rst:1382 msgid "" "Regular expressions are a complicated topic. Did this document help you " "understand them? Were there parts that were unclear, or Problems you " "encountered that weren't covered here? If so, please send suggestions for " "improvements to the author." msgstr "" "Las expresiones regulares son un tema complicado. ¿Le ayudó este documento a " "comprenderlas? ¿Hubo partes que no estaban claras o problemas que encontró " "que no se trataron aquí? Si es así, envíe sugerencias de mejora al autor." #: ../Doc/howto/regex.rst:1387 msgid "" "The most complete book on regular expressions is almost certainly Jeffrey " "Friedl's Mastering Regular Expressions, published by O'Reilly. " "Unfortunately, it exclusively concentrates on Perl and Java's flavours of " "regular expressions, and doesn't contain any Python material at all, so it " "won't be useful as a reference for programming in Python. (The first " "edition covered Python's now-removed :mod:`!regex` module, which won't help " "you much.) Consider checking it out from your library." msgstr "" "El libro más completo sobre expresiones regulares es casi con certeza " "*Mastering Regular Expressions de Jeffrey Friedl*, publicado por *O'Reilly*. " "Desafortunadamente, se concentra exclusivamente en los tipos de expresiones " "regulares de Perl y Java, y no contiene ningún material de Python, por lo " "que no será útil como referencia para la programación en Python. (La primera " "edición cubría el módulo :mod:`!regex` de Python, ahora eliminado, que no le " "ayudará mucho.) Considere sacarlo de su biblioteca."