Tuesday 11 July 2017

Python Regex Match 5 Digits Forex


Expressão Regular HOWTO Este documento é um tutorial introdutório para usar expressões regulares em Python com o módulo re. Ele fornece uma introdução mais suave do que a seção correspondente na Referência da Biblioteca. Introdução O módulo re foi adicionado em Python 1.5 e fornece padrões de expressão regulares em estilo Perl. Versões anteriores do Python veio com o módulo regex, que forneceu padrões do Emacs. O módulo regex foi removido completamente em Python 2.5. Expressões regulares (chamadas REs, ou regexes, ou padrões regex) são essencialmente uma linguagem de programação minúscula e altamente especializada incorporada dentro do Python e disponibilizada através do módulo re. Usando este pequeno idioma, você especifica as regras para o conjunto de seqüências possíveis que você deseja combinar este conjunto pode conter frases em inglês, ou endereços de email, ou comandos TeX, ou qualquer coisa que você gosta. Você pode então fazer perguntas como 8220Does esta seqüência de caracteres correspondem ao pattern8221, ou 8220Is há uma correspondência para o padrão em qualquer lugar neste string8221. Você também pode usar REs para modificar uma string ou dividi-la de várias maneiras. Os padrões de expressão regular são compilados em uma série de bytecodes que são então executados por um mecanismo de correspondência escrito em C. Para uso avançado, pode ser necessário prestar muita atenção à forma como o mecanismo irá executar uma determinada RE e escrever a RE em um De forma a produzir um bytecode que funcione mais rápido. Otimização isn8217t coberto neste documento, porque exige que você tenha uma boa compreensão do correspondente engine8217s internals. A linguagem de expressão regular é relativamente pequena e restrita, portanto, nem todas as possíveis tarefas de processamento de seqüência de caracteres podem ser feitas usando expressões regulares. Há também tarefas que podem ser feitas com expressões regulares, mas as expressões se tornam muito complicadas. Nestes casos, você pode ser melhor escrever código Python para fazer o processamento, enquanto o código Python será mais lento do que uma expressão regular elaborada, ele também provavelmente será mais compreensível. Padrões Simples Começaremos aprendendo sobre as expressões regulares mais simples possíveis. Como as expressões regulares são usadas para operar em strings, we8217ll começa com a tarefa mais comum: caracteres correspondentes. Para uma explicação detalhada da ciência computacional subjacente a expressões regulares (autômatos finitos determinísticos e não determinísticos), você pode consultar quase qualquer livro sobre compiladores de escrita. Personagens correspondentes A maioria das letras e caracteres simplesmente se combinam. Por exemplo, o teste de expressão regular corresponderá exatamente ao teste de string. (Você pode ativar um modo sem diferenciação de maiúsculas e minúsculas que permitiria que este RE correspondesse a Test ou TEST e mais sobre isso mais tarde). Existem exceções a esta regra, alguns caracteres são metacaracteres especiais. E don8217t correspondem a si mesmos. Em vez disso, eles sinalizam que alguma coisa fora do comum deve ser combinada, ou eles afetam outras porções do RE, repetindo-os ou mudando seu significado. Muito deste documento é dedicado a discutir vários metacaracteres eo que eles fazem. Aqui uma lista completa dos metacaracteres seus significados serão discutidos no resto deste HOWTO. Os primeiros metacaracteres que olhamos são e. Eles são usados ​​para especificar uma classe de caracteres, que é um conjunto de caracteres que você deseja combinar. Os caracteres podem ser listados individualmente, ou um intervalo de caracteres pode ser indicado dando dois caracteres e separando-os por um -. Por exemplo, abc irá corresponder a qualquer um dos caracteres a. B. Ou c é o mesmo que a-c. Que usa um intervalo para expressar o mesmo conjunto de caracteres. Se você quisesse combinar apenas letras minúsculas, sua RE seria a-z. Metacaracteres não são ativos dentro de classes. Por exemplo, akm irá corresponder a qualquer um dos caracteres a. K. M. Ou é geralmente um metacaracter, mas dentro de uma classe de caráter despojado de sua natureza especial. Você pode combinar os caracteres não listados dentro da classe, complementando o conjunto. Isso é indicado pela inclusão de um como o primeiro caractere da classe fora de uma classe de caracteres simplesmente corresponderá ao caractere. Por exemplo, 5 irá corresponder a qualquer caractere, exceto 5. Talvez o metacaracter mais importante seja a barra invertida,. Como nos literais de string Python, a barra invertida pode ser seguida por vários caracteres para sinalizar várias seqüências especiais. It8217s também usado para escapar de todos os metacaracteres para que você ainda pode combiná-los em padrões, por exemplo, se você precisa corresponder a ou. Você pode precedê-los com uma barra invertida para remover seu significado especial: ou. Algumas das seqüências especiais começando com representam conjuntos predefinidos de caracteres que são muitas vezes úteis, como o conjunto de dígitos, o conjunto de letras, ou o conjunto de qualquer coisa que isn8217t whitespace. As seqüências especiais predefinidas a seguir são um subconjunto dos disponíveis. As classes equivalentes são para padrões de cadeia de bytes. Para obter uma lista completa de seqüências e definições de classes expandidas para padrões de Cadeia de caracteres Unicode, consulte a última parte da Sintaxe de expressões regulares. D Corresponde a qualquer dígito decimal que seja equivalente à classe 0-9. D Corresponde a qualquer caractere de não-dígito que é equivalente à classe 0-9. S Corresponde a qualquer caractere de espaço em branco que seja equivalente à classe tnrfv. S Corresponde a qualquer caractere não-espaço em branco que é equivalente à classe tnrfv. W Corresponde a qualquer caractere alfanumérico equivalente à classe a-zA-Z0-9. W Corresponde a qualquer caractere não alfanumérico equivalente à classe a-zA-Z0-9. Essas seqüências podem ser incluídas dentro de uma classe de caracteres. Por exemplo,. É uma classe de caracteres que irá corresponder a qualquer caractere de espaço em branco, ou, ou. . O metacaractere final nesta seção é. Ele corresponde a qualquer coisa, exceto um caractere de nova linha, e existe um modo alternativo (re. DOTALL) onde ele irá igualar até mesmo uma nova linha. . É freqüentemente usado onde você quer corresponder a qualquer caractere 8222. Repetindo Coisas Ser capaz de combinar diferentes conjuntos de caracteres é a primeira coisa que as expressões regulares podem fazer que já não é possível com os métodos disponíveis em strings. No entanto, se essa fosse a única capacidade adicional de regexes, eles não seriam muito de um avanço. Outra capacidade é que você pode especificar que partes do RE devem ser repetidas um certo número de vezes. O primeiro metacaractere para repetir coisas que nós olhamos é. Doesn8217t corresponde ao caractere literal em vez disso, especifica que o caractere anterior pode ser correspondido zero ou mais vezes, em vez de exatamente uma vez. Por exemplo, o gato irá corresponder ct (0 caracteres a), cat (1 a), caaat (3 caracteres a) e assim por diante. O mecanismo de RE tem várias limitações internas decorrentes do tamanho do tipo int C8217s que irá impedi-lo de combinar mais de 2 bilhões de caracteres que você provavelmente não tem memória suficiente para construir uma Cadeia de caracteres tão grande, então você não deve correr para esse limite. Repetições como são gananciosos ao repetir um RE, o motor de correspondência irá tentar repeti-lo tantas vezes quanto possível. Se as porções posteriores do padrão não coincidirem, o mecanismo correspondente voltará a fazer backup e tentará novamente com menos repetições. Um exemplo passo-a-passo tornará isso mais óbvio. Consideremos a expressão abcdb. Isso corresponde à letra a. Zero ou mais letras da classe bcd. E finalmente termina com um b. Agora imagine combinar este RE contra a string abcbd. Tente b novamente. Desta vez o personagem na posição atual é b. Assim que sucede. O fim do RE foi agora atingido, e tem correspondência abcb. Isso demonstra como o mecanismo de correspondência vai tão longe quanto pode no início, e se nenhuma correspondência for encontrada, em seguida, irá progressivamente voltar e repetir o resto do RE uma e outra vez. Ele voltará até que ele tenha tentado zero correspondências para bcd. E se isso falhar subseqüentemente, o motor concluirá que a corda doesn8217t fósforo o RE em tudo. Outro metacaractere de repetição é. Que corresponde a uma ou mais vezes. Preste muita atenção à diferença entre e corresponda a zero ou mais vezes, de modo que qualquer coisa que esteja sendo repetida pode não estar presente de forma alguma, enquanto requer pelo menos uma ocorrência. Para usar um exemplo semelhante, o gato irá coincidir com cat (1 a), caaat (3 a 8216s), mas won8217t correspondência ct. Há mais dois qualificadores repetitivos. O caractere de ponto de interrogação. Corresponde a uma vez ou zero vezes você pode pensar nisso como marcando algo como sendo opcional. Por exemplo, home-brew corresponde a homebrew ou home-brew. O qualificador repetitivo mais complicado é. Onde m e n são inteiros decimais. Este qualificador significa que deve haver pelo menos m repetições, e no máximo n. Por exemplo, a / b irá corresponder a / b. A // b. E a /// b. Ele venceu ab match. Que não tem barras, ou a //// b. Que tem quatro. Você pode omitir m ou n nesse caso, um valor razoável é assumido para o valor ausente. Omitindo m é interpretado como um limite inferior de 0, enquanto omitindo n resulta em um limite superior do infinito 8212 na verdade, o limite superior é o limite de 2 bilhões mencionado anteriormente, mas isso também poderia ser infinito. Os leitores de uma curva reducionista podem notar que os três outros qualificadores podem ser expressos usando esta notação. é o mesmo que . é equivalente a . E é o mesmo que. It8217s melhor usar. . ou. Quando você pode, simplesmente porque eles são mais curtos e mais fáceis de ler. Usando expressões regulares Agora que we8217ve olhou para algumas expressões regulares simples, como é que realmente usá-los em Python O módulo re fornece uma interface para o mecanismo de expressão regular, permitindo que você compilar REs em objetos e, em seguida, executar correspondências com eles. Compilando expressões regulares Expressões regulares são compiladas em objetos de padrão, que possuem métodos para várias operações, como a pesquisa de correspondências de padrões ou a realização de substituições de seqüências de caracteres. Repile () também aceita um argumento flags opcional, usado para habilitar várias características especiais e variações de sintaxe. Vamos passar as configurações disponíveis mais tarde, mas por enquanto um único exemplo fará: O RE é passado para repile () como uma string. As REs são manipuladas como seqüências de caracteres porque as expressões regulares são parte do núcleo da linguagem Python e nenhuma sintaxe especial foi criada para expressá-las. (Há aplicações que precisam de REs em tudo, então não há necessidade de bloat a especificação de linguagem, incluindo-os.) Em vez disso, o módulo re é simplesmente um módulo de extensão C incluído com Python, assim como o soquete ou módulos zlib. Colocar REs em strings mantém a linguagem Python mais simples, mas tem uma desvantagem que é o tópico da próxima seção. A praga de barra invertida Como mencionado anteriormente, as expressões regulares usam o caractere de barra invertida () para indicar formulários especiais ou para permitir que caracteres especiais sejam usados ​​sem invocar seu significado especial. Isto está em conflito com o uso de Python8217s do mesmo caractere para a mesma finalidade em literais de seqüência de caracteres. Let8217s dizer que você quer escrever um RE que coincide com a seqüência seção. Que pode ser encontrado em um arquivo LaTeX. Para descobrir o que escrever no código do programa, comece com a seqüência desejada para ser correspondido. Em seguida, você deve escapar de qualquer barra invertida e outros metacaracteres, precedendo-os com uma barra invertida, resultando na seção seqüência de caracteres. A seqüência resultante que deve ser passada para repile () deve ser seção. No entanto, para expressar isso como um literal de Cadeia de caracteres Python, ambas as barras invertidas devem ser escapadas novamente. Encontre todas as subseqüências onde o RE coincide e retorna-as como um iterador. Match () e search () return None se nenhuma correspondência puder ser encontrada. Se eles forem bem-sucedidos, uma instância de objeto de correspondência é retornada, contendo informações sobre a correspondência: onde ela começa e termina, a substring correspondida e muito mais. Você pode aprender sobre isso experimentando interativamente com o módulo re. Se você tiver Tkinter disponível, você também pode querer olhar para Ferramentas / scripts / redemo. py. Um programa de demonstração incluído com a distribuição Python. Ele permite que você insira REs e strings e exibe se o RE corresponde ou falha. Redemo. py pode ser bastante útil ao tentar depurar um RE complicado. Phil Schwartz8217s Kodos também é uma ferramenta interativa para desenvolver e testar padrões RE. Este HOWTO usa o interpretador Python padrão para seus exemplos. Primeiro, execute o interpretador Python, importe o módulo re e compile um RE: Agora, você pode tentar combinar várias seqüências de caracteres contra o RE a-z. Uma seqüência de caracteres vazia não deve coincidir, uma vez que significa 8216uma ou mais repetições8217. Match () deve retornar None neste caso, o que fará com que o interpretador para imprimir nenhuma saída. Você pode imprimir explicitamente o resultado de match () para tornar isso claro. Agora, vamos tentar em uma seqüência de caracteres que ele deve corresponder, como o tempo. Nesse caso, match () retornará um objeto de correspondência. Então você deve armazenar o resultado em uma variável para uso posterior. Agora você pode consultar o objeto de correspondência para obter informações sobre a seqüência correspondente. As instâncias de objeto de correspondência também têm vários métodos e atributos os mais importantes são: Tentar esses métodos logo esclarecerá seu significado: group () retorna a substring que foi correspondida pelo RE. Start () e end () retornam o índice inicial e final da correspondência. Span () retorna os índices inicial e final em uma única tupla. Uma vez que o método match () apenas verifica se o RE coincide com o início de uma string, start () sempre será zero. No entanto, o método search () de padrões varre a seqüência de caracteres, portanto, a correspondência pode não começar em zero nesse caso. Em programas reais, o estilo mais comum é armazenar o objeto de correspondência em uma variável e, em seguida, verifique se ele era Nenhum. Isso normalmente se parece com: Dois métodos padrão retornam todas as correspondências para um padrão. Findall () retorna uma lista de strings correspondentes: findall () tem que criar a lista inteira antes que ela possa ser retornada como resultado. O método finditer () retorna uma seqüência de coincidência de instâncias de objeto como um iterador. 1 Funções no nível do módulo Você não precisa criar um objeto padrão e chamar seus métodos. O módulo re também fornece funções de nível superior chamadas match (). pesquisa(). encontrar tudo(). sub(). e assim por diante. Essas funções tomam os mesmos argumentos que o método de padrão correspondente, com a seqüência de RE adicionada como o primeiro argumento e ainda retornar None ou uma ocorrência de objeto de correspondência. Sob o capô, essas funções simplesmente criar um objeto padrão para você e chamar o método apropriado sobre ele. Eles também armazenam o objeto compilado em um cache, para futuras chamadas usando o mesmo RE são mais rápidos. Se você usar essas funções de nível de módulo, ou você deve obter o padrão e chamar seus métodos a si mesmo Essa escolha depende da freqüência com que o RE será usado e em seu estilo de codificação pessoal. Se o RE está sendo usado em apenas um ponto no código, então as funções do módulo são provavelmente mais conveniente. Se um programa contém muitas expressões regulares ou reutiliza as mesmas em vários locais, então talvez valha a pena coletar todas as definições em um só lugar, em uma seção de código que compila todas as REs antes do tempo. Para tirar um exemplo da biblioteca padrão, aqui é um extrato do módulo xmllib depreciado: Eu geralmente prefiro trabalhar com o objeto compilado, mesmo para uso único, mas poucas pessoas serão tão puristas quanto a isso, como eu . Bandeiras de Compilação As bandeiras de Compilação permitem modificar alguns aspectos de como funcionam as expressões regulares. As bandeiras estão disponíveis no módulo re com dois nomes, um nome longo como IGNORECASE e um formulário curto, de uma letra como I. (Se você estiver familiarizado com os modificadores de padrão Perl8217s, os formulários de uma letra usam as mesmas letras do formulário curto De re. VERBOSE é re. X., por exemplo.) Múltiplos sinalizadores podem ser especificados por bitwise OR-ing-los re. I re. M define os sinalizadores I e M, por exemplo. Aqui está uma tabela das bandeiras disponíveis, seguida de uma explicação mais detalhada de cada uma delas. Faz várias fugas como w. B. S e d dependentes da base de dados de caracteres Unicode. Execute uma classe de caracteres correspondente que não diferencie maiúsculas e minúsculas e as seqüências literais corresponderão às letras ignorando o caso. Por exemplo, A-Z corresponderá letras minúsculas, também, e Spam irá corresponder Spam. Spam. Ou spAM. Este doesn8217t lowercasing levar o local atual em conta que se você também definir o sinalizador LOCALE. Faça w. W. b. E B. dependente da localidade atual. Locais são uma característica da biblioteca C destinada a ajudar na escrita de programas que levam em conta as diferenças de linguagem. Por exemplo, se you8217re processamento de texto em francês, you8217d quer ser capaz de escrever w para coincidir com palavras, mas w só coincide com a classe de caracteres A-Za-z won8217t ou match. Se o sistema estiver configurado corretamente e uma localidade francesa for selecionada, certas funções C direcionarão o programa que também deve ser considerado uma letra. Definir o sinalizador LOCALE ao compilar uma expressão regular fará com que o objeto compilado resultante use essas funções C para w isso é mais lento, mas também permite w para coincidir com palavras francesas como you8217d esperar. (E haven8217t foram explicados ainda que eles serão apresentados na seção More Metacharacters.) Normalmente corresponde apenas no início da seqüência de caracteres, e corresponde apenas no final da seqüência de caracteres e imediatamente antes da nova linha (se houver) no final da seqüência de caracteres. Quando este sinalizador é especificado, corresponde ao início da seqüência de caracteres e no início de cada linha dentro da seqüência de caracteres, imediatamente após cada nova linha. Da mesma forma, o metacaracteres corresponde ao final da seqüência e no final de cada linha (imediatamente antes de cada nova linha). Faz o. Caracteres especiais correspondem a qualquer caractere, incluindo uma nova linha sem este sinalizador,. Irá corresponder a qualquer coisa, exceto uma nova linha. Faça w. W. b. B. d. D. s e S dependente da base de dados de propriedades de caracteres Unicode. Este sinalizador permite escrever expressões regulares que são mais legíveis, concedendo-lhe mais flexibilidade na forma como pode formatá-las. Quando esse sinalizador foi especificado, o espaço em branco dentro da seqüência RE é ignorado, exceto quando o espaço em branco está em uma classe de caracteres ou precedido por uma barra invertida sem escape que permite organizar e recuar a RE mais claramente. Este sinalizador também permite que você coloque comentários dentro de um RE que será ignorado pelos comentários do mecanismo são marcados por um that8217s nem em uma classe de caracteres ou precedido por uma barra invertida sem escape. Por exemplo, here8217s um RE que usa re. VERBOSE ver como é mais fácil de ler Sem a configuração detalhada, o RE seria assim: No exemplo acima, Python8217s concatenação automática de literais de seqüência foi usado para quebrar a RE Em pedaços menores, mas é ainda mais difícil de entender do que a versão que usa re. VERBOSE. Mais Poder de Padrão Até agora, apenas cobrimos uma parte das características das expressões regulares. Nesta seção, we8217ll cobrir alguns novos metacaracteres e como usar grupos para recuperar partes do texto que foi correspondido. Mais Metacaracteres Há alguns metacaracteres que ainda não foram cobertos. A maioria deles será coberta nesta seção. Alguns dos metacaracteres restantes a serem discutidos são asserções de largura zero. Eles não fazem com que o motor avança através da corda, em vez disso, eles não consomem nenhum personagem em tudo, e simplesmente ter sucesso ou falhar. Por exemplo, b é uma afirmação de que a posição atual está localizada em um limite de palavra, a posição não é alterada pelo b. Isso significa que afirmações de largura zero nunca devem ser repetidas, porque se elas coincidirem uma vez em um determinado local, elas podem obviamente ser combinadas um número infinito de vezes. Alternação, ou o operador 8220or8221. Se A e B são expressões regulares, AB irá coincidir com qualquer seqüência de caracteres que corresponda a A ou B. tem precedência muito baixa, a fim de fazê-lo funcionar razoavelmente quando você estiver alternando seqüências de caracteres de vários caracteres. CrowServo irá corresponder Crow ou Servo. Não Cro. Um w ou um S. e um ervo. Para corresponder a um literal. usar . Ou incluí-lo dentro de uma classe de caracteres, como em. Corresponde no início das linhas. A menos que o sinalizador MULTILINE tenha sido definido, este só irá corresponder no início da cadeia. No modo MULTILINE, isso também coincide imediatamente após cada nova linha dentro da seqüência. Por exemplo, se você deseja combinar a palavra De apenas no início de uma linha, o RE a usar é De. Corresponde no final de uma linha, que é definida como o fim da seqüência de caracteres, ou qualquer local seguido por um caractere de nova linha. Para corresponder a um literal. Use ou inclua dentro de uma classe de personagem, como em. A Corresponde somente no início da seqüência. Quando não no modo MULTILINE, A e são efetivamente os mesmos. No modo MULTILINE, they8217re diferente: A ainda corresponde apenas no início da seqüência de caracteres, mas pode coincidir em qualquer local dentro da seqüência de caracteres que segue um caractere de nova linha. Z Corresponde somente ao final da seqüência. B Limite de palavras. Esta é uma afirmação de largura zero que corresponde apenas ao início ou ao fim de uma palavra. Uma palavra é definida como uma seqüência de caracteres alfanuméricos, portanto, o final de uma palavra é indicado por espaço em branco ou um caractere não-alfanumérico. O exemplo a seguir corresponde à classe somente quando it8217s uma palavra completa que won8217t correspondem quando it8217s contido dentro de outra palavra. Há duas sutilezas que você deve se lembrar ao usar esta seqüência especial. Em primeiro lugar, esta é a pior colisão entre os literais de string do Python8217s e as sequências de expressão regulares. Em literais de Cadeia de Caracteres Python8217s, b é o caractere de retrocesso, valor ASCII 8. Se você não estiver usando seqüências de caracteres brutas, então o Python converterá o b em um espaço de retorno e sua resposta será igual a como você espera. O exemplo a seguir parece o mesmo que o nosso RE anterior, mas omite o r na frente da seqüência RE. Em segundo lugar, dentro de uma classe de caracteres, onde não há uso para esta asserção, b representa o caractere de retrocesso, para compatibilidade com literais de Cadeia de caracteres Python8217s. B Outra asserção de largura zero, isto é o oposto de b. Somente correspondente quando a posição atual não está em um limite de palavra. Agrupamento Muitas vezes você precisa obter mais informações do que apenas se o RE corresponde ou não. As expressões regulares são freqüentemente usadas para dissecar strings escrevendo um RE dividido em vários subgrupos que combinam com diferentes componentes de interesse. Por exemplo, uma linha de cabeçalho RFC-822 é dividida em um nome de cabeçalho e um valor, separados por um:. Como este: Isto pode ser tratado escrevendo uma expressão regular que corresponde a uma linha de cabeçalho inteira e tem um grupo que corresponde ao nome do cabeçalho e outro grupo que corresponde ao valor do header8217s. Os grupos são marcados pelos metacaracteres (.). (E) têm muito o mesmo significado que eles fazem em expressões matemáticas que agrupam as expressões contidas dentro deles, e você pode repetir o conteúdo de um grupo com um qualificador de repetição, como. . Ou. Por exemplo, (ab) corresponderá zero ou mais repetições de ab. Os grupos indicados com (.) Também capturam o índice inicial e final do texto que correspondem a este pode ser recuperado passando um argumento para group (). começar(). fim(). E span (). Os grupos são numerados começando com 0. O grupo 0 está sempre presente it8217s o RE inteiro, assim que os métodos do objeto do fósforo todos têm o grupo 0 como seu argumento do defeito. Mais tarde, veremos como expressar grupos que não captam a extensão de texto que eles correspondem. Os subgrupos são numerados da esquerda para a direita, de 1 para cima. Os grupos podem ser aninhados para determinar o número, basta contar os caracteres de parêntese de abertura, indo da esquerda para a direita. Group () pode ser passado vários números de grupo de cada vez, caso em que ele irá retornar uma tupla contendo os valores correspondentes para esses grupos. O método groups () retorna uma tupla que contém as seqüências de caracteres para todos os subgrupos, de 1 até a quantidade que existem. Backreferences em um padrão permitem que você especifique que o conteúdo de um grupo de captura anterior também deve ser encontrado no local atual na seqüência de caracteres. Por exemplo, 1 terá êxito se o conteúdo exato do grupo 1 pode ser encontrado na posição atual e falha em contrário. Lembre-se de que os literais de string Python8217s também usam uma barra invertida seguida de números para permitir a inclusão de caracteres arbitrários em uma string, por isso não se esqueça de usar uma string bruta ao incorporar backreferences em uma RE. Por exemplo, o seguinte RE detecta palavras dobradas em uma seqüência de caracteres. Backreferences como este aren8217t muitas vezes útil para apenas pesquisar através de uma Cadeia de caracteres 8212 existem poucos formatos de texto que repetir dados desta forma 8212 mas you8217ll logo descobrir que they8217re muito útil ao executar substituições de Cadeia de caracteres. Grupos Não-Capturadores e Nomeados As REs Elaboradas podem usar muitos grupos, tanto para capturar substrings de interesse como para agrupar e estruturar a própria RE. Em REs complexas, torna-se difícil acompanhar os números de grupo. Existem dois recursos que ajudam com esse problema. Ambos usam uma sintaxe comum para extensões de expressão regular, então vamos ver isso primeiro. O Perl 5 adicionou vários recursos adicionais às expressões regulares padrão eo módulo Python re suporta a maioria deles. Teria sido difícil escolher novos metacaracteres de teclas únicas ou novas seqüências especiais começando por representar os novos recursos sem tornar as expressões regulares do Perl8217 confusamente diferentes das REs padrão. Se você escolheu amp como um novo metacaracteres, por exemplo, expressões antigas estariam assumindo que amp era um caractere normal e wouldn8217t escapou-lo por escrito amp ou amp. A solução escolhida pelos desenvolvedores do Perl foi usar (.) Como a sintaxe da extensão. Imediatamente após um parêntese foi um erro de sintaxe porque o. Não teria nada a repetir, por isso este didn8217t introduzir quaisquer problemas de compatibilidade. Os caracteres imediatamente após o. (Foo) é uma coisa (uma asserção lookahead positiva) e (: foo) é outra coisa (um grupo não-captura que contém a subexpressão foo). O Python adiciona uma sintaxe de extensão à sintaxe da extensão Perl8217s. Se o primeiro caracter depois do ponto de interrogação é um P. você sabe que it8217s uma extensão that8217s específico para Python. Atualmente, existem duas dessas extensões: (Pltnamegt.) Define um grupo nomeado e (Pname) é uma referência para um grupo nomeado. Se futuras versões do Perl 5 adicionarem recursos semelhantes usando uma sintaxe diferente, o módulo re será alterado para suportar a nova sintaxe, preservando a sintaxe específica do Python para compatibilidade8217s. Agora que examinamos a sintaxe de extensão geral, podemos retornar aos recursos que simplificam o trabalho com grupos em REs complexas. Como os grupos são numerados da esquerda para a direita e uma expressão complexa pode usar muitos grupos, pode tornar-se difícil acompanhar a numeração correta. Modificar um RE tão complexo também é irritante: insira um novo grupo perto do início e altere os números de tudo o que o segue. Às vezes você vai querer usar um grupo para coletar uma parte de uma expressão regular, mas não está interessado em recuperar o conteúdo do grupo. Você pode tornar esse fato explícito usando um grupo que não captura: (.). Onde você pode substituir o. Com qualquer outra expressão regular. Exceto pelo fato de que você não pode recuperar o conteúdo do que o grupo correspondeu, um grupo não-captura se comporta exatamente como um grupo de captura, você pode colocar qualquer coisa dentro dele, repita-o com um metacaractere de repetição como. E aniná-lo dentro de outros grupos (captura ou não-captura). (.) É particularmente útil quando se modifica um padrão existente, pois você pode adicionar novos grupos sem alterar como todos os outros grupos estão numerados. Deve-se mencionar que não existe diferença de desempenho na busca entre os grupos de captura e não de captura, nem a forma é mais rápida que a outra. Um recurso mais significativo é denominado grupos: em vez de referir-se a eles por números, os grupos podem ser referenciados por um nome. A sintaxe para um grupo nomeado é uma das extensões específicas do Python: (Pltnamegt.). Nome é, obviamente, o nome do grupo. Os grupos nomeados também se comportam exatamente como os grupos de captura e, adicionalmente, associam um nome a um grupo. Os métodos de objeto de correspondência que lidam com grupos de captura todos aceitam inteiros que se referem ao grupo por número ou seqüências de caracteres que contêm o nome de grupo desejado. Grupos nomeados ainda recebem números, portanto, você pode recuperar informações sobre um grupo de duas maneiras: Grupos nomeados são úteis porque permitem que você use nomes facilmente lembrados, em vez de ter que lembrar números. Here8217s um exemplo RE do módulo imaplib: It8217s obviamente muito mais fácil de recuperar m. group (zonem). Em vez de ter que se lembrar de recuperar o grupo 9. A sintaxe para backreferences em uma expressão como (.) 1 refere-se ao número do grupo. There8217s naturalmente uma variante que usa o nome do grupo em vez do número. Esta é outra extensão do Python: (Pname) indica que o conteúdo do grupo chamado name deve ser novamente correspondido no ponto atual. A expressão regular para encontrar palavras duplicadas, (bw) s1 também pode ser escrita como (Pltwordgtbw) s (Pword): Asserções Lookahead Outra asserção de largura zero é a afirmação lookahead. As asserções de Lookahead estão disponíveis tanto na forma positiva quanto na negativa, e se parecem com isto: (.) ​​Asserção positiva do lookahead. Isto sucede se a expressão regular contida, representada aqui por. Corresponde com êxito ao local atual e falha em contrário. Mas, uma vez que a expressão contida foi tentada, o mecanismo correspondente não avança em todo o resto do padrão é testado exatamente onde a asserção começou. (.) Asserção negativa do lookahead. Isto é o oposto da asserção positiva que sucede se a expressão contida não corresponde à posição actual na cadeia. Para tornar isso concreto, vamos olhar para um caso em que um lookahead é útil. Considere um padrão simples para combinar um nome de arquivo e dividi-lo em um nome base e uma extensão, separados por um. Por exemplo, em news. rc. News é o nome base, e rc é a extensão filename8217s. O padrão para coincidir com isso é bastante simples: Observe que o. Precisa ser tratada especialmente porque um metacaracter I8217ve colocá-lo dentro de uma classe de caracteres. Observe também o arrastar isso é adicionado para garantir que todo o resto da seqüência de caracteres deve ser incluído na extensão. Esta expressão regular corresponde a foo. bar e autoexec. bat e sendmail. cf e impressters. conf. Agora, considere complicar o problema um pouco e se você quiser coincidir com nomes de arquivos onde a extensão não é morcego. Algumas tentativas incorretas:.b. A primeira tentativa acima tenta excluir o bastão exigindo que o primeiro caractere da extensão não seja a b. Isso é errado, porque o padrão também não coincide com foo. bar. A expressão fica mais confusa quando você tenta corrigir a primeira solução, exigindo que um dos seguintes casos corresponda: o primeiro caractere da extensão isn8217t b o segundo caracter isn8217t a ou o terceiro caracter isn8217t t. Isso aceita foo. bar e rejeita autoexec. bat. Mas requer uma extensão de três letras e won8217t aceitar um nome de arquivo com uma extensão de duas letras, como sendmail. cf. Vamos complicar o padrão novamente em um esforço para consertá-lo. 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 . The pattern8217s 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. A negative lookahead cuts through all this confusion: .(bat). The negative lookahead means: if the expression bat doesn8217t 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. 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 : Modifying Strings Up to this point, we8217ve simply performed searches against a static string. Regular expressions are also commonly used to modify strings in various ways, using the following pattern methods: Splitting Strings The split() method of a pattern splits a string apart wherever the RE matches, returning a list of the pieces. It8217s similar to the split() method of strings but provides much more generality in the delimiters that you can split by split() only supports splitting by whitespace or by a fixed string. As you8217d expect, there8217s a module-level re. split() function, too. 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. 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. Sometimes you8217re 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: The module-level function re. split() adds the RE to be used as the first argument, but is otherwise the same. Search and Replace Another common task is to find all the matches for a pattern, and replace them with a different string. The sub() method takes a replacement value, which can be either a string or a function, and the string to be processed. Returns the string obtained by replacing the leftmost non-overlapping occurrences of the RE in string by the replacement replacement . If the pattern isn8217t found, string is returned unchanged. 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. Here8217s a simple example of using the sub() method. It replaces colour names with the word colour : The subn() method does the same work, but returns a 2-tuple containing the new string value and the number of replacements that were performed: Empty matches are replaced only when they8217re not adjacent to a previous match. 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 j 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. This example matches the word section followed by a string enclosed in . and changes section to subsection : There8217s also a syntax for referring to named groups as defined by the (Pltnamegt. ) syntax. gltnamegt will use the substring matched by the group named name. and gltnumbergt uses the corresponding group number. glt2gt is therefore equivalent to 2. but isn8217t ambiguous in a replacement string such as glt2gt0. ( 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. 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 match object argument for the match and can use this information to compute the desired replacement string and return it. In the following example, the replacement function translates decimals into hexadecimal: When using the module-level 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(quot(i)bquot, quotxquot, quotbbbb BBBBquot) returns x x . Common Problems Regular expressions are a powerful tool for some applications, but in some ways their behaviour isn8217t intuitive and at times they don8217t behave the way you may expect them to. This section will point out some of the most common pitfalls. Use String Methods Sometimes using the re module is a mistake. If you8217re matching a fixed string, or a single character class, and you8217re not using any re features such as the IGNORECASE flag, then the full power of regular expressions may not be required. Strings have several methods for performing operations with fixed strings and they8217re usually much faster, because the implementation is a single small C loop that8217s been optimized for the purpose, instead of the large, more generalized regular expression engine. One example might be replacing a single fixed string with another one for example, you might replace word with deed. re. sub() seems like the function to use for this, but consider the replace() method. Note that 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 bwordb. in order to require that word have a word boundary on either side. This takes the job beyond replace() 8216s abilities.) 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 translate() is capable of doing both tasks and will be faster than any regular expression operation can be. In short, before turning to the re module, consider whether your problem can be solved with a faster and simpler string method. match() versus search() The match() function only checks if the RE matches at the beginning of the string while search() will scan forward through the string for a match. It8217s important to keep this distinction in mind. Remember, match() will only report a successful match which will start at 0 if the match wouldn8217t start at zero, match() will not report it. On the other hand, search() will scan forward through the string, reporting the first match it finds. Sometimes you8217ll be tempted to keep using re. match(). and just add . to the front of your RE. Resist this temptation and use 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. 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 re. search() instead. Greedy versus Non-Greedy 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 you8217re 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 doesn8217t work because of the greedy nature of . . The RE matches the lt in lthtmlgt. and the . consumes the rest of the string. There8217s still more left in the RE, though, and the gt can8217t 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 gt. The final match extends from the lt in lthtmlgt to the gt in lt/titlegt. which isn8217t what you want. In this case, the solution is to use the non-greedy qualifiers . . or . which match as little text as possible. In the above example, the gt is tried immediately after the first lt matches, and when it fails, the engine advances a character at a time, retrying the gt at every step. This produces just the right result: (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 you8217ve 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.) Using re. VERBOSE By now you8217ve probably noticed that regular expressions are a very compact notation, but they8217re not terribly readable. REs of moderate complexity can become lengthy collections of backslashes, parentheses, and metacharacters, making them difficult to read and understand. For such REs, specifying the re. VERBOSE flag when compiling the regular expression can be helpful, because it allows you to format the regular expression more clearly. The re. VERBOSE flag has several effects. Whitespace in the regular expression that isn8217t inside a character class is ignored. This means that an expression such as dog cat is equivalent to the less readable dogcat. 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: This is far more readable than: Feedback Regular expressions are a complicated topic. Did this document help you understand them Were there parts that were unclear, or Problems you encountered that weren8217t covered here If so, please send suggestions for improvements to the author. The most complete book on regular expressions is almost certainly Jeffrey Friedl8217s Mastering Regular Expressions, published by O8217Reilly. Unfortunately, it exclusively concentrates on Perl and Java8217s flavours of regular expressions, and doesn8217t contain any Python material at all, so it won8217t be useful as a reference for programming in Python. (The first edition covered Python8217s now-removed regex module, which won8217t help you much.) Consider checking it out from your library. Introduced in Python 2.2.2.7.2. re 8212 Regular expression operations This module provides regular expression matching operations similar to those found in Perl. Both patterns and strings to be searched can be Unicode strings as well as 8-bit strings. However, Unicode strings and 8-bit strings cannot be mixed: that is, you cannot match an Unicode string with a byte pattern or vice-versa similarly, when asking for a substitution, the replacement string must be of the same type as both the pattern and the search string. Regular expressions use the backslash character ( ) to indicate special forms or to allow special characters to be used without invoking their special meaning. This collides with Python8217s usage of the same character for the same purpose in string literals for example, to match a literal backslash, one might have to write as the pattern string, because the regular expression must be . and each backslash must be expressed as inside a regular Python string literal. The solution is to use Python8217s raw string notation for regular expression patterns backslashes are not handled in any special way in a string literal prefixed with r . So rquotnquot is a two-character string containing and n . while quotnquot is a one-character string containing a newline. Usually patterns will be expressed in Python code using this raw string notation. It is important to note that most regular expression operations are available as module-level functions and RegexObject methods. The functions are shortcuts that don8217t require you to compile a regex object first, but miss some fine-tuning parameters. Mastering Regular Expressions Book on regular expressions by Jeffrey Friedl, published by O8217Reilly. The second edition of the book no longer covers Python at all, but the first edition covered writing good regular expression patterns in great detail. 7.2.1. Regular Expression Syntax A regular expression (or RE) specifies a set of strings that matches it the functions in this module let you check if a particular string matches a given regular expression (or if a given regular expression matches a particular string, which comes down to the same thing). Regular expressions can be concatenated to form new regular expressions if A and B are both regular expressions, then AB is also a regular expression. In general, if a string p matches A and another string q matches B . the string pq will match AB. This holds unless A or B contain low precedence operations boundary conditions between A and B or have numbered group references. Thus, complex expressions can easily be constructed from simpler primitive expressions like the ones described here. For details of the theory and implementation of regular expressions, consult the Friedl book referenced above, or almost any textbook about compiler construction. A brief explanation of the format of regular expressions follows. For further information and a gentler presentation, consult the Regular Expression HOWTO . Regular expressions can contain both special and ordinary characters. Most ordinary characters, like A . a . or 0 . are the simplest regular expressions they simply match themselves. You can concatenate ordinary characters, so last matches the string last . (In the rest of this section, we8217ll write RE8217s in this special style . usually without quotes, and strings to be matched in single quotes .) Some characters, like or ( . are special. Special characters either stand for classes of ordinary characters, or affect how the regular expressions around them are interpreted. Regular expression pattern strings may not contain null bytes, but can specify the null byte using the number notation, e. g. x00 . The special characters are: . (Dot.) In the default mode, this matches any character except a newline. If the DOTALL flag has been specified, this matches any character including a newline. (Caret.) Matches the start of the string, and in MULTILINE mode also matches immediately after each newline. Matches the end of the string or just before the newline at the end of the string, and in MULTILINE mode also matches before a newline. foo matches both 8216foo8217 and 8216foobar8217, while the regular expression foo matches only 8216foo8217. More interestingly, searching for foo. in foo1nfoo2n matches 8216foo28217 normally, but 8216foo18217 in MULTILINE mode searching for a single in foon will find two (empty) matches: one just before the newline, and one at the end of the string. Causes the resulting RE to match 0 or more repetitions of the preceding RE, as many repetitions as are possible. ab will match 8216a8217, 8216ab8217, or 8216a8217 followed by any number of 8216b8217s. Causes the resulting RE to match 1 or more repetitions of the preceding RE. ab will match 8216a8217 followed by any non-zero number of 8216b8217s it will not match just 8216a8217. Causes the resulting RE to match 0 or 1 repetitions of the preceding RE. ab will match either 8216a8217 or 8216ab8217. . . . The . . and qualifiers are all greedy they match as much text as possible. Sometimes this behaviour isn8217t desired if the RE lt. gt is matched against ltH1gttitlelt/H1gt . it will match the entire string, and not just ltH1gt . Adding after the qualifier makes it perform the match in non-greedy or minimal fashion as few characters as possible will be matched. Using . in the previous expression will match only ltH1gt . Specifies that exactly m copies of the previous RE should be matched fewer matches cause the entire RE not to match. For example, a will match exactly six a characters, but not five. Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to match as many repetitions as possible. For example, a will match from 3 to 5 a characters. Omitting m specifies a lower bound of zero, and omitting n specifies an infinite upper bound. As an example, a b will match aaaab or a thousand a characters followed by a b . but not aaab . The comma may not be omitted or the modifier would be confused with the previously described form. Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to match as few repetitions as possible. This is the non-greedy version of the previous qualifier. For example, on the 6-character string aaaaaa . a will match 5 a characters, while a will only match 3 characters. Either escapes special characters (permitting you to match characters like . . and so forth), or signals a special sequence special sequences are discussed below. If you8217re not using a raw string to express the pattern, remember that Python also uses the backslash as an escape sequence in string literals if the escape sequence isn8217t recognized by Python8217s parser, the backslash and subsequent character are included in the resulting string. However, if Python would recognize the resulting sequence, the backslash should be repeated twice. This is complicated and hard to understand, so it8217s highly recommended that you use raw strings for all but the simplest expressions. Used to indicate a set of characters. Characters can be listed individually, or a range of characters can be indicated by giving two characters and separating them by a - . Special characters are not active inside sets. For example, akm will match any of the characters a . k . m . or a-z will match any lowercase letter, and a-zA-Z0-9 matches any letter or digit. Character classes such as w or S (defined below) are also acceptable inside a range, although the characters they match depends on whether ASCII or LOCALE mode is in force. If you want to include a or a - inside a set, precede it with a backslash, or place it as the first character. The pattern will match . por exemplo. You can match the characters not within a range by complementing the set. This is indicated by including a as the first character of the set elsewhere will simply match the character. For example, 5 will match any character except 5 . and will match any character except . Note that inside the special forms and special characters lose their meanings and only the syntaxes described here are valid. For example, . . ( . ) . and so on are treated as literals inside . and backreferences cannot be used inside . AB . where A and B can be arbitrary REs, creates a regular expression that will match either A or B. An arbitrary number of REs can be separated by the in this way. This can be used inside groups (see below) as well. As the target string is scanned, REs separated by are tried from left to right. When one pattern completely matches, that branch is accepted. This means that once A matches, B will not be tested further, even if it would produce a longer overall match. In other words, the operator is never greedy. To match a literal . use . or enclose it inside a character class, as in . (. ) Matches whatever regular expression is inside the parentheses, and indicates the start and end of a group the contents of a group can be retrieved after a match has been performed, and can be matched later in the string with the number special sequence, described below. To match the literals ( or ) . use ( or ) . or enclose them inside a character class: ( ) . (. ) This is an extension notation (a following a ( is not meaningful otherwise). The first character after the determines what the meaning and further syntax of the construct is. Extensions usually do not create a new group (Pltnamegt. ) is the only exception to this rule. Following are the currently supported extensions. (aiLmsux) (One or more letters from the set a . i . L . m . s . u . x .) The group matches the empty string the letters set the corresponding flags: re. A (ASCII-only matching), re. I (ignore case), re. L (locale dependent), re. M (multi-line), re. S (dot matches all), and re. X (verbose), for the entire regular expression. (The flags are described in Module Contents .) This is useful if you wish to include the flags as part of the regular expression, instead of passing a flag argument to the repile() function. Note that the (x) flag changes how the expression is parsed. It should be used first in the expression string, or after one or more whitespace characters. If there are non-whitespace characters before the flag, the results are undefined. (. ) A non-capturing version of regular parentheses. Matches whatever regular expression is inside the parentheses, but the substring matched by the group cannot be retrieved after performing a match or referenced later in the pattern. (Pltnamegt. ) Similar to regular parentheses, but the substring matched by the group is accessible within the rest of the regular expression via the symbolic group name name . Group names must be valid Python identifiers, and each group name must be defined only once within a regular expression. A symbolic group is also a numbered group, just as if the group were not named. So the group named id in the example below can also be referenced as the numbered group 1 . For example, if the pattern is (Pltidgta-zA-Zw) . the group can be referenced by its name in arguments to methods of match objects, such as m. group(id) or m. end(id) . and also by name in the regular expression itself (using (Pid) ) and replacement text given to. sub() (using gltidgt ). (Pname) Matches whatever text was matched by the earlier group named name . (. ) A comment the contents of the parentheses are simply ignored. (. ) Matches if . matches next, but doesn8217t consume any of the string. This is called a lookahead assertion. For example, Isaac (Asimov) will match Isaac only if it8217s followed by Asimov . (. ) Matches if . doesn8217t match next. This is a negative lookahead assertion. For example, Isaac (Asimov) will match Isaac only if it8217s not followed by Asimov . (lt. ) Matches if the current position in the string is preceded by a match for . that ends at the current position. This is called a positive lookbehind assertion . (ltabc)def will find a match in abcdef . since the lookbehind will back up 3 characters and check if the contained pattern matches. The contained pattern must only match strings of some fixed length, meaning that abc or ab are allowed, but a and a are not. Note that patterns which start with positive lookbehind assertions will never match at the beginning of the string being searched you will most likely want to use the search() function rather than the match() function: This example looks for a word following a hyphen: (lt. ) Matches if the current position in the string is not preceded by a match for . . This is called a negative lookbehind assertion . Similar to positive lookbehind assertions, the contained pattern must only match strings of some fixed length. Patterns which start with negative lookbehind assertions may match at the beginning of the string being searched. ((id/name)yes-patternno-pattern) Will try to match with yes-pattern if the group with given id or name exists, and with no-pattern if it doesn8217t. no-pattern is optional and can be omitted. For example, (lt)(w64w(:.w))((1)gt) is a poor email matching pattern, which will match with ltuser64hostgt as well as user64host . but not with ltuser64host nor user64hostgt . The special sequences consist of and a character from the list below. If the ordinary character is not on the list, then the resulting RE will match the second character. For example, matches the character . number Matches the contents of the group of the same number. Groups are numbered starting from 1. For example, (.) 1 matches the the or 55 55 . but not the end (note the space after the group). This special sequence can only be used to match one of the first 99 groups. If the first digit of number is 0, or number is 3 octal digits long, it will not be interpreted as a group match, but as the character with octal value number . Inside the and of a character class, all numeric escapes are treated as characters. A Matches only at the start of the string. b Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of Unicode alphanumeric or underscore characters, so the end of a word is indicated by whitespace or a non-alphanumeric, non-underscore Unicode character. Note that formally, b is defined as the boundary between a w and a W character (or vice versa). By default Unicode alphanumerics are the ones used, but this can be changed by using the ASCII flag. Inside a character range, b represents the backspace character, for compatibility with Python8217s string literals. B Matches the empty string, but only when it is not at the beginning or end of a word. This is just the opposite of b . so word characters are Unicode alphanumerics or the underscore, although this can be changed by using the ASCII flag. d For Unicode (str) patterns: Matches any Unicode digit (which includes 0-9 . and also many other digit characters). If the ASCII flag is used only 0-9 is matched (but the flag affects the entire regular expression, so in such cases using an explicit 0-9 may be a better choice). For 8-bit (bytes) patterns: Matches any decimal digit this is equivalent to 0-9 . D Matches any character which is not a Unicode decimal digit. This is the opposite of d . If the ASCII flag is used this becomes the equivalent of 0-9 (but the flag affects the entire regular expression, so in such cases using an explicit 0-9 may be a better choice). s For Unicode (str) patterns: Matches Unicode whitespace characters (which includes tnrfv . and also many other characters, for example the non-breaking spaces mandated by typography rules in many languages). If the ASCII flag is used, only tnrfv is matched (but the flag affects the entire regular expression, so in such cases using an explicit tnrfv may be a better choice). For 8-bit (bytes) patterns: Matches characters considered whitespace in the ASCII character set this is equivalent to tnrfv . S Matches any character which is not a Unicode whitespace character. This is the opposite of s . If the ASCII flag is used this becomes the equivalent of tnrfv (but the flag affects the entire regular expression, so in such cases using an explicit tnrfv may be a better choice). w For Unicode (str) patterns: Matches Unicode word characters this includes most characters that can be part of a word in any language, as well as numbers and the underscore. If the ASCII flag is used, only a-zA-Z0-9 is matched (but the flag affects the entire regular expression, so in such cases using an explicit a-zA-Z0-9 may be a better choice). For 8-bit (bytes) patterns: Matches characters considered alphanumeric in the ASCII character set this is equivalent to a-zA-Z0-9 . W Matches any character which is not a Unicode word character. This is the opposite of w . If the ASCII flag is used this becomes the equivalent of a-zA-Z0-9 (but the flag affects the entire regular expression, so in such cases using an explicit a-zA-Z0-9 may be a better choice). Z Matches only at the end of the string. Most of the standard escapes supported by Python string literals are also accepted by the regular expression parser: Octal escapes are included in a limited form: If the first digit is a 0, or if there are three octal digits, it is considered an octal escape. Otherwise, it is a group reference. As for string literals, octal escapes are always at most three digits in length. 7.2.2. Matching vs Searching Python offers two different primitive operations based on regular expressions: match checks for a match only at the beginning of the string, while search checks for a match anywhere in the string (this is what Perl does by default). Note that match may differ from search even when using a regular expression beginning with . matches only at the start of the string, or in MULTILINE mode also immediately following a newline. The 8220match8221 operation succeeds only if the pattern matches at the start of the string regardless of mode, or at the starting position given by the optional pos argument regardless of whether a newline precedes it. 7.2.3. Module Contents The module defines several functions, constants, and an exception. Some of the functions are simplified versions of the full featured methods for compiled regular expressions. Most non-trivial applications always use the compiled form. Compile a regular expression pattern into a regular expression object, which can be used for matching using its match() and search() methods, described below. The expression8217s behaviour can be modified by specifying a flags value. Values can be any of the following variables, combined using bitwise OR (the operator). is equivalent to but using repile() and saving the resulting regular expression object for reuse is more efficient when the expression will be used several times in a single program. The compiled versions of the most recent patterns passed to re. match() . re. search() or repile() are cached, so programs that use only a few regular expressions at a time needn8217t worry about compiling regular expressions. Make w . W . b . B. d . D . 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. Note that for backward compatibility, the re. U flag still exists (as well as its synonym re. UNICODE and its embedded counterpart (u) ), but these are redundant in Python 3 since matches are Unicode by default for strings (and Unicode matching isn8217t allowed for bytes). re. I re. IGNORECASE Perform case-insensitive matching expressions like A-Z will match lowercase letters, too. This is not affected by the current locale and works for Unicode characters as expected. re. L re. LOCALE Make w . W . b . B. s and S dependent on the current locale. The use of this flag is discouraged as the locale mechanism is very unreliable, and it only handles one 8220culture8221 at a time anyway you should use Unicode matching instead, which is the default in Python 3 for Unicode (str) patterns. re. M re. MULTILINE When specified, the pattern character matches at the beginning of the string and at the beginning of each line (immediately following each newline) and the pattern character matches at the end of the string and at the end of each line (immediately preceding each newline). By default, matches only at the beginning of the string, and only at the end of the string and immediately before the newline (if any) at the end of the string. re. S re. DOTALL Make the . special character match any character at all, including a newline without this flag, . will match anything except a newline. re. X re. VERBOSE This flag allows you to write regular expressions that look nicer. Whitespace within the pattern is ignored, except when in a character class or preceded by an unescaped backslash, and, when a line contains a neither in a character class or preceded by an unescaped backslash, all characters from the leftmost such through the end of the line are ignored. That means that the two following regular expression objects that match a decimal number are functionally equal: re. search ( pattern . string . flags ) Scan through string looking for a location where the regular expression pattern produces a match, and return a corresponding MatchObject instance. Return None if no position in the string matches the pattern note that this is different from finding a zero-length match at some point in the string. re. match ( pattern . string . flags ) If zero or more characters at the beginning of string match the regular expression pattern . return a corresponding MatchObject instance. Return None if the string does not match the pattern note that this is different from a zero-length match. If you want to locate a match anywhere in string . use search() instead. Split string by the occurrences of pattern . If capturing parentheses are used in pattern . then the text of all groups in the pattern are also returned as part of the resulting list. If maxsplit is nonzero, at most maxsplit splits occur, and the remainder of the string is returned as the final element of the list. If there are capturing groups in the separator and it matches at the start of the string, the result will start with an empty string. The same holds for the end of the string: That way, separator components are always found at the same relative indices within the result list (e. g. if there8217s one capturing group in the separator, the 0th, the 2nd and so forth). Note that split will never split a string on an empty pattern match. For example: Changed in version 3.1: Added the optional flags argument. re. findall ( pattern . string . flags ) Return all non-overlapping matches of pattern in string . as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result unless they touch the beginning of another match. re. finditer ( pattern . string . flags ) Return an iterator yielding MatchObject instances over all non-overlapping matches for the RE pattern in string . The string is scanned left-to-right, and matches are returned in the order found. Empty matches are included in the result unless they touch the beginning of another match. re. sub ( pattern . repl . string . count . flags ) Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl . If the pattern isn8217t found, string is returned unchanged. repl can be a string or a function if it 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 linefeed, and so forth. Unknown escapes such as j are left alone. Backreferences, such as 6 . are replaced with the substring matched by group 6 in the pattern. For example: If repl is a function, it is called for every non-overlapping occurrence of pattern . The function takes a single match object argument, and returns the replacement string. For example: The pattern may be a string or an RE object. The optional argument count is the maximum number of pattern occurrences to be replaced count must be a non-negative integer. If omitted or zero, all occurrences will be replaced. Empty matches for the pattern are replaced only when not adjacent to a previous match, so sub(x, -, abc) returns - a-b-c - . In addition to character escapes and backreferences as described above, gltnamegt will use the substring matched by the group named name . as defined by the (Pltnamegt. ) syntax. gltnumbergt uses the corresponding group number glt2gt is therefore equivalent to 2 . but isn8217t ambiguous in a replacement such as glt2gt0 . 20 would be interpreted as a reference to group 20, not a reference to group 2 followed by the literal character 0 . The backreference glt0gt substitutes in the entire substring matched by the RE. Changed in version 3.1: Added the optional flags argument. Perform the same operation as sub() . but return a tuple (newstring, numberofsubsmade) . Changed in version 3.1: Added the optional flags argument. re. escape ( string ) Return string with all non-alphanumerics backslashed this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it. re. purge ( ) Clear the regular expression cache. exception re. error Exception raised when a string passed to one of the functions here is not a valid regular expression (for example, it might contain unmatched parentheses) or when some other error occurs during compilation or matching. It is never an error if a string contains no match for a pattern. 7.2.4. Regular Expression Objects The RegexObject class supports the following methods and attributes: Scan through string looking for a location where this regular expression produces a match, and return a corresponding MatchObject instance. Return None if no position in the string matches the pattern note that this is different from finding a zero-length match at some point in the string. The optional second parameter pos gives an index in the string where the search is to start it defaults to 0 . This is not completely equivalent to slicing the string the pattern character matches at the real beginning of the string and at positions just after a newline, but not necessarily at the index where the search is to start. The optional parameter endpos limits how far the string will be searched it will be as if the string is endpos characters long, so only the characters from pos to endpos - 1 will be searched for a match. If endpos is less than pos . no match will be found, otherwise, if rx is a compiled regular expression object, rx. search(string, 0, 50) is equivalent to rx. search(string:50, 0) . If zero or more characters at the beginning of string match this regular expression, return a corresponding MatchObject instance. Return None if the string does not match the pattern note that this is different from a zero-length match. The optional pos and endpos parameters have the same meaning as for the search() method. If you want to locate a match anywhere in string . use search() instead. split ( string . maxsplit0 ) Identical to the split() function, using the compiled pattern. findall ( string . pos . endpos ) Similar to the findall() function, using the compiled pattern, but also accepts optional pos and endpos parameters that limit the search region like for match() . finditer ( string . pos . endpos ) Similar to the finditer() function, using the compiled pattern, but also accepts optional pos and endpos parameters that limit the search region like for match() . sub ( repl . string . count0 ) Identical to the sub() function, using the compiled pattern. subn ( repl . string . count0 ) Identical to the subn() function, using the compiled pattern. flags The flags argument used when the RE object was compiled, or 0 if no flags were provided. groups The number of capturing groups in the pattern. groupindex A dictionary mapping any symbolic group names defined by (Pltidgt) to group numbers. The dictionary is empty if no symbolic groups were used in the pattern. pattern The pattern string from which the RE object was compiled. 7.2.5. Match Objects Match Objects always have a boolean value of True . so that you can test whether e. g. match() resulted in a match with a simple if statement. They support the following methods and attributes: expand ( template ) Return the string obtained by doing backslash substitution on the template string template . as done by the sub() method. Escapes such as n are converted to the appropriate characters, and numeric backreferences ( 1 . 2 ) and named backreferences ( glt1gt . gltnamegt ) are replaced by the contents of the corresponding group. group ( group1 . . ) Returns one or more subgroups of the match. If there is a single argument, the result is a single string if there are multiple arguments, the result is a tuple with one item per argument. Without arguments, group1 defaults to zero (the whole match is returned). If a groupN argument is zero, the corresponding return value is the entire matching string if it is in the inclusive range 1..99, it is the string matching the corresponding parenthesized group. If a group number is negative or larger than the number of groups defined in the pattern, an IndexError exception is raised. If a group is contained in a part of the pattern that did not match, the corresponding result is None . If a group is contained in a part of the pattern that matched multiple times, the last match is returned. If the regular expression uses the (Pltnamegt. ) syntax, the groupN arguments may also be strings identifying groups by their group name. If a string argument is not used as a group name in the pattern, an IndexError exception is raised. A moderately complicated example: 7.2.6.3. Avoiding recursion If you create regular expressions that require the engine to perform a lot of recursion, you may encounter a RuntimeError exception with the message maximum recursion limit exceeded. For example, You can often restructure your regular expression to avoid recursion. Simple uses of the pattern are special-cased to avoid recursion. Thus, the above regular expression can avoid recursion by being recast as Begin a-zA-Z0-9 end . As a further benefit, such regular expressions will run faster than their recursive equivalents. 7.2.6.4. search() vs. match() In a nutshell, match() only attempts to match a pattern at the beginning of a string where search() will match a pattern anywhere in a string. For example: The following applies only to regular expression objects like those created with repile(quotpatternquot) . not the primitives re. match(pattern, string) or re. search(pattern, string) . match() has an optional second parameter that gives an index in the string where the search is to start: 7.2.6.5. Making a Phonebook split() splits a string into a list delimited by the passed pattern. The method is invaluable for converting textual data into data structures that can be easily read and modified by Python as demonstrated in the following example that creates a phonebook. First, here is the input. Normally it may come from a file, here we are using triple-quoted string syntax: The entries are separated by one or more newlines. Now we convert the string into a list with each nonempty line having its own entry: Finally, split each entry into a list with first name, last name, telephone number, and address. We use the maxsplit parameter of split() because the address has spaces, our splitting pattern, in it: The . pattern matches the colon after the last name, so that it does not occur in the result list. With a maxsplit of 4 . we could separate the house number from the street name: 7.2.6.6. Text Munging sub() replaces every occurrence of a pattern with a string or the result of a function. This example demonstrates using sub() with a function to 8220munge8221 text, or randomize the order of all the characters in each word of a sentence except for the first and last characters: 7.2.6.7. Finding all Adverbs findall() matches all occurrences of a pattern, not just the first one as search() does. For example, if one was a writer and wanted to find all of the adverbs in some text, he or she might use findall() in the following manner: 7.2.6.8. Finding all Adverbs and their Positions If one wants more information about all matches of a pattern than the matched text, finditer() is useful as it provides instances of MatchObject instead of strings. Continuing with the previous example, if one was a writer who wanted to find all of the adverbs and their positions in some text, he or she would use finditer() in the following manner: 7.2.6.9. Raw String Notation Raw string notation ( rquottextquot ) keeps regular expressions sane. Without it, every backslash ( ) in a regular expression would have to be prefixed with another one to escape it. For example, the two following lines of code are functionally identical: When one wants to match a literal backslash, it must be escaped in the regular expression. With raw string notation, this means rquotquot . Without raw string notation, one must use quotquot . making the following lines of code functionally identical:Python Regular Expressions A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. Regular expressions are widely used in UNIX world. The module re provides full support for Perl-like regular expressions in Python. The re module raises the exception re. error if an error occurs while compiling or using a regular expression. We would cover two important functions, which would be used to handle regular expressions. But a small thing first: There are various characters, which would have special meaning when they are used in regular expression. To avoid any confusion while dealing with regular expressions, we would use Raw Strings as rexpression . The match Function This function attempts to match RE pattern to string with optional flags . Here is the syntax for this function minus Here is the description of the parameters: This is the regular expression to be matched. This is the string, which would be searched to match the pattern at the beginning of string. You can specify different flags using bitwise OR (). These are modifiers, which are listed in the table below. The re. match function returns a match object on success, None on failure. We use group(num) or groups() function of match object to get matched expression. Match Object Methods This method returns entire match (or specific subgroup num) This method returns all matching subgroups in a tuple (empty if there werent any) Example When the above code is executed, it produces following result minus The search Function This function searches for first occurrence of RE pattern within string with optional flags . Here is the syntax for this function: Here is the description of the parameters: This is the regular expression to be matched. This is the string, which would be searched to match the pattern anywhere in the string. You can specify different flags using bitwise OR (). These are modifiers, which are listed in the table below. The re. search function returns a match object on success, none on failure. We use group(num) or groups() function of match object to get matched expression. Match Object Methods This method returns entire match (or specific subgroup num) This method returns all matching subgroups in a tuple (empty if there werent any) Example When the above code is executed, it produces following result minus Matching Versus Searching Python offers two different primitive operations based on regular expressions: match checks for a match only at the beginning of the string, while search checks for a match anywhere in the string (this is what Perl does by default). Example When the above code is executed, it produces the following result minus Search and Replace One of the most important re methods that use regular expressions is sub . Syntax This method replaces all occurrences of the RE pattern in string with repl . substituting all occurrences unless max provided. This method returns modified string. Example When the above code is executed, it produces the following result minus Regular Expression Modifiers: Option Flags Regular expression literals may include an optional modifier to control various aspects of matching. The modifiers are specified as an optional flag. You can provide multiple modifiers using exclusive OR (), as shown previously and may be represented by one of these minus

No comments:

Post a Comment