---
title: Expressões Regulares
slug: homologacao-atmosphere/expressoes-regulares
description: Learn how to effectively use regular expressions in Python for string searching and manipulation with this comprehensive document. Discover how to extract specific parts of a string using the `regex_search` filter, extract all occurrences of a regex patte
createdAt: 2021-12-16T17:31:52.000Z
---

## Resumo

-

## Pesquisando strings com expressões regulares

Para pesquisar em uma string ou extrair partes de uma string, utiliza-se o filtro: `regex_search`

```python
# Extrair o nome do banco de dados de uma string
{{ 'server1/database42' | regex_search('database[0-9]+') }}
# => 'database42'

# Exemplo para uma pesquisa sem distinção entre maiúsculas e minúsculas no modo multilinha
{{ 'foo\nBAR' | regex_search('^bar', multiline=True, ignorecase=True) }}
# => 'BAR'

# Extrair o ID do servidor e do banco de dados de uma string
{{ 'server1/database42' | regex_search('server([0-9]+)/database([0-9]+)', '\\1', '\\2') }}
# => ['1', '42']

# Extrair o dividendo e o divisor de uma divisão
{{ '21/42' | regex_search('(?P<dividend>[0-9]+)/(?P<divisor>[0-9]+)', '\\g<dividend>', '\\g<divisor>') }}
# => ['21', '42']
```



O filtro retornará uma string vazia se não encontrar uma correspondência:

```python
{{ 'atmosphere' | regex_search('foobar') }}
# => ''
```



Para extrair todas as ocorrências de correspondências de regex em uma string, utiliza-se o filtro `regex_findall`:

```python
# Retorna uma lista de todos os endereços IPv4 na string
{{ 'Some DNS servers are 8.8.8.8 and 8.8.4.4' | regex_findall('\\b(?:[0-9]{1,3}\\.){3}[0-9]{1,3}\\b') }}
# => ['8.8.8.8', '8.8.4.4']

# Retorna todas as linhas que terminam com "ar"
{{ 'CAR\ntar\nfoo\nbar\n' | regex_findall('^.ar$', multiline=True, ignorecase=True) }}
# => ['CAR', 'tar', 'bar']
```



Para substituir o texto em uma string por regex, utiliza-se o filtro `regex_replace`:

```python
# Converter "foobar" para "bar"
{{ 'foobar' | regex_replace('^f.*o(.*)$', '\\1') }}
# => 'bar'

# Converter "localhost:80" para "localhost, 80" utilizando grupos nomeados
{{ 'localhost:80' | regex_replace('^(?P<host>.+):(?P<port>\\d+)$', '\\g<host>, \\g<port>') }}
# => 'localhost, 80'

# Converter "localhost:80" para "localhost"
{{ 'localhost:80' | regex_replace(':80') }}
# => 'localhost'

# Comentar todas as linhas que terminam com "ar"
{{ 'CAR\ntar\nfoo\nbar\n' | regex_replace('^(.ar)$', '#\\1', multiline=True, ignorecase=True) }}
# => '#CAR\n#tar\nfoo\n#bar\n'
```



