SlideShare uma empresa Scribd logo
1 de 49
Baixar para ler offline
O que há de errado com
expressões regulares?
*elas são NP-completas, só que não.

juanlopes.net/devday2013
Logs de aplicação
Contém muita informação

186.247.10.187 - - GET
/gnews/gnews_600/gnews_1374508780437_1374508780437_1470.ts HTTP/1.1 "200"
346672 "-" 0.232 "AppleCoreMedia/1.0.0.10B329 (iPad; U; CPU OS 6_1_3 like
Mac OS X; pt_br)" "-" - [MISS] 0.006 ms
201.51.232.169 - - GET
/gnews/gnews_1000/gnews_1374508779820_1374508779820_1466.ts HTTP/1.1 "200"
552156 "http://globotv.globo.com/globo-news/globo-news-ao-vivo/v/globonewsao-vivo/61910/" 0.480 "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36" "-" - [MISS] 0.008
ms
201.7.186.60 - - GET /ber2/ber2_400/playlist.m3u8 HTTP/1.1 "200" 538 "http:
//g1.globo.com/jornal-hoje/ao-vivo.html" 0.001 "Mozilla/5.0 (Windows NT
6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72
Safari/537.36" "-" - [EXPIRED] 0.001 ms
Logs de aplicação
Exemplo: IP de origem

186.247.10.187 - - GET
/gnews/gnews_600/gnews_1374508780437_1374508780437_1470.ts HTTP/1.1 "200"
346672 "-" 0.232 "AppleCoreMedia/1.0.0.10B329 (iPad; U; CPU OS 6_1_3 like
Mac OS X; pt_br)" "-" - [MISS] 0.006 ms
201.51.232.169 - - GET
/gnews/gnews_1000/gnews_1374508779820_1374508779820_1466.ts HTTP/1.1 "200"
552156 "http://globotv.globo.com/globo-news/globo-news-ao-vivo/v/globonewsao-vivo/61910/" 0.480 "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36" "-" - [MISS] 0.008
ms
201.7.186.60 - - GET /ber2/ber2_400/playlist.m3u8 HTTP/1.1 "200" 538 "http:
//g1.globo.com/jornal-hoje/ao-vivo.html" 0.001 "Mozilla/5.0 (Windows NT
6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72
Safari/537.36" "-" - [EXPIRED] 0.001 ms
Logs de aplicação
Exemplo: identificador do vídeo

186.247.10.187 - - GET
/gnews/gnews_600/gnews_1374508780437_1374508780437_1470.ts HTTP/1.1 "200"
346672 "-" 0.232 "AppleCoreMedia/1.0.0.10B329 (iPad; U; CPU OS 6_1_3 like
Mac OS X; pt_br)" "-" - [MISS] 0.006 ms
201.51.232.169 - - GET
/gnews/gnews_1000/gnews_1374508779820_1374508779820_1466.ts HTTP/1.1 "200"
552156 "http://globotv.globo.com/globo-news/globo-news-ao-vivo/v/globonewsao-vivo/61910/" 0.480 "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36" "-" - [MISS] 0.008
ms
201.7.186.60 - - GET /ber2/ber2_400/playlist.m3u8 HTTP/1.1 "200" 538 "http:
//g1.globo.com/jornal-hoje/ao-vivo.html" 0.001 "Mozilla/5.0 (Windows NT
6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72
Safari/537.36" "-" - [EXPIRED] 0.001 ms
Logs de aplicação
Exemplo: URL da página em que o vídeo foi reproduzido

186.247.10.187 - - GET
/gnews/gnews_600/gnews_1374508780437_1374508780437_1470.ts HTTP/1.1 "200"
346672 "-" 0.232 "AppleCoreMedia/1.0.0.10B329 (iPad; U; CPU OS 6_1_3 like
Mac OS X; pt_br)" "-" - [MISS] 0.006 ms
201.51.232.169 - - GET
/gnews/gnews_1000/gnews_1374508779820_1374508779820_1466.ts HTTP/1.1 "200"
552156 "http://globotv.globo.com/globo-news/globo-news-ao-vivo/v/globonewsao-vivo/61910/" 0.480 "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36" "-" - [MISS] 0.008
ms
201.7.186.60 - - GET /ber2/ber2_400/playlist.m3u8 HTTP/1.1 "200" 538 "http:
//g1.globo.com/jornal-hoje/ao-vivo.html" 0.001 "Mozilla/5.0 (Windows NT
6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72
Safari/537.36" "-" - [EXPIRED] 0.001 ms
Expressões regulares
Para extrair estas informações

(?<ip>[d.]+)s-s-sGETs(?<path>/?(?
<stream>[^/]*)/?[^.]*.?(?<extension>
[^s?]*))(?<querystring>[^s]*)s[^s]*s"
(?<status>d*)"s(?<body_bytes_sent>[d]*)
s"(?<http_referer>[^"]*)"s[d.]+s"(?
<user_agent>[^"]*)"s"(?<forwarded_for>[^"]
*)"s-s[(?<cache_status>[w-]*)]s(?
<upstream_response_time>[^s]*)sms.*
Benchmarks são limitados
Essa palestra é basicamente para dizer o óbvio

sljit.sourceforge.net/regex_perf.html
Russ Cox
Um dos maiores committers da linguagem Go

“RE2, provides most of the
functionality of PCRE using a C++
interface very close to PCRE's, but it
guarantees linear time execution and
a fixed stack footprint. RE2 is now in
widespread use at Google, both in
Code Search and in internal systems
like Sawzall and Bigtable”
PyRex
github.com/juanplopes/pyrex
Complexidade de algoritmos
Como medir a complexidade de:
(?<ip>[d.]+)s-s-sGETs(?<path>/?(?<stream>[^/]*)/?[^.]*.?(?<extension>[^s?]*))
(?<querystring>[^s]*)s[^s]*s"(?<status>d*)"s(?<body_bytes_sent>[d]*)s"(?
<http_referer>[^"]*)"s[d.]+s"(?<user_agent>[^"]*)"s"(?<forwarded_for>[^"]*)"s-s
[(?<cache_status>[w-]*)]s(?<upstream_response_time>[^s]*)sms.*
Repositórios online
Não estão livres de regexes maliciosas
Repositórios online
^([a-zA-Z0-9])(([-.]|[_]+)?([a-zA-Z0-9]+))*(@){1}[a-z0-9]+[.]{1}(([a-z]{2,3})|([a-z]{2,3}[.]{1}[a-z]{2,3}))$
Acontece nos melhores projetos
Mas não deveria
Regex: (a?a)+b
Regexes não deveriam se comportar assim:
Expressões regulares em
tempo linear?
Expressões regulares em
tempo linear?
SIM e NÃO?!
Expressões regulares em
tempo linear?
SIM e NÃO?!
Woody Allen Noam Chomsky
Pai da linguística moderna (e um ativista barulhento)

“A generative grammar
must be a system of rules
that can iterate to
generate an indefinitely
large number of
structures.”
Hierarquia de Chomsky
Essencial para a teoria de linguagens de programação

IRRESTRITAS

SENSÍVEIS AO CONTEXTO

LIVRES DE CONTEXTO

REGULARES
Hierarquia de Chomsky
Cada gramática exige uma máquina para reconhecê-la

Gramática

Autômato

Regras

0

Irrestrita

Máquina de Turing

α→β

1

Sensível ao
contexto

Autômato linearmente
limitado

αSβ → αγβ

2

Livre de contexto

Autômato de pilha

S→γ

Autômato finito

S→ε
S→a
S → aT

3

Regular
Expressões regulares
Denotam linguagens, hum…, regulares.
Forma

Descrição

ER1

∅

Linguagem vazia

ER2

ε

Linguagem contendo apenas cadeia vazia

ER3

a

Linguagem contendo apenas cadeia a

ER4

α|β

União entre Lα e Lβ

ER5

αβ

Concatenação entre Lα e Lβ

ER6

α*

Fecho Kleene sobre Lα
Autômatos finitos
Reconhecem linguagens regulares
abc?d
a

b

c

d

ε

ε

abcd*
a

b

c

d

ε
Uma notação simplificada
Para representar autômatos finitos

Autômato
a

ε

Notação
a

Instrução
CONSUME
JUMP
MATCH
Uma notação simplificada
Mesmos exemplos em nova notação
abc?d
a

b

c

d

abcd*
a

b

c

d
Conversão
Expressão regular → autômato finito
Expressão

Autômato

a

a

αβ

α

β

α|β

α

α?

α

α+
α*

α
α

β
Conversão
Útil para representar o autômato de diversas formas
ER

abc?d

abcd+

(a?a)+b

Autômato
a

a

b

b

a

c

c

a

d

d

b

Array

Instruções

'a', 'b', [1, 2], 'c', 'd'

0000:
0001:
0002:
0003:
0004:
0005:

CONSUME 'a'
CONSUME 'b'
JUMP (1, 2)
CONSUME 'c'
CONSUME 'd'
MATCH!

'a', 'b', 'c', 'd', [1, -1]

0000:
0001:
0002:
0003:
0004:
0005:

CONSUME a
CONSUME b
CONSUME c
CONSUME d
JUMP (1, -1)
MATCH!

[1, 2], 'a', 'a', [1, -3], 'b'

0000:
0001:
0002:
0003:
0004:
0005:

JUMP (1, 2)
CONSUME a
CONSUME a
JUMP (1, -3)
CONSUME b
MATCH!
NFA: Autômato Finito
Não Determinístico

c
INDETERMINISMO

d
Indeterminismo
Potencial exponencial devastador, em alguns casos
Expressão
(a?a)+b

Autômato
a

0000:
0001:
0002:
0003:
0004:
0005:

a

Array
b

[1, 2], 'a', 'a', [1, -3], 'b'

JUMP (1, 2)
CONSUME 'a'
CONSUME 'a'
JUMP (1, -3)
CONSUME 'b'
MATCH!
Catastrophic
Backtracking
CATASTROPHIC
BACKTRACKING
PCRE

POSIX
Simular autômato
Várias formas, com vantagens e desvantagens
Método

Vantagem

Desvantagem

Backtracking

Implementação simples

Simulação exponencial

Backtracking com
memorização

Implementação simples;
complexidade polinomial

Chamadas recursivas;
acesso aleatório à entrada

Converter para DFA

Simulação linear

Conversão exponencial

Simulação paralela

Sem chamadas recursivas;
acesso sequencial à entrada

Simulação superlinear

Conversão
preguiçosa para DFA

Boa localidade de referência;
melhor caso linear

Pior caso ainda superlinear
Simular autômato
Paralela: melhor custo/benefício
Método

Vantagem

Desvantagem

Backtracking

Implementação simples

Simulação exponencial

Backtracking com
memorização

Implementação simples;
complexidade polinomial

Chamadas recursivas;
acesso aleatório à entrada

Converter para DFA

Simulação linear

Conversão exponencial

Simulação paralela

Sem chamadas recursivas;
acesso sequencial à entrada

Simulação superlinear

Conversão
preguiçosa para DFA

Boa localidade de referência;
melhor caso linear

Pior caso ainda superlinear
PyRex
O código cabe num slide o/
Benchmarks: (a?a)+b
Caso O(2^n): exponencialmente melhor
Benchmarks: a*b
Caso O(n): pior por um fator constante
Benchmarks: a*a*a*a*a*b
Caso O(n^5): polinomialmente melhor (e Ruby rouba)
Expressões regulares em
tempo linear?
SIM e NÃO?!
Linguagens não-regulares
O que elas tem a ver com expressões regulares?

IRRESTRITAS

SENSÍVEIS AO CONTEXTO

LIVRES DE CONTEXTO

REGULARES
Linguagens não-regulares
Alguns exemplos

Exemplos
Parênteses
aninhados

(()()(())), (((()))), ...

"Squares"

DogDog, CatCat, WikiWiki, ...

an b n

ab, aabb, aaabbb, ...
Linguagens não-regulares
Alguns exemplos

IRRESTRITAS

SENSÍVEIS AO CONTEXTO

anbncn, "squares"

LIVRES DE CONTEXTO

anbn, parênteses

REGULARES
Linguagens não-regulares
Expressões regulares que as reconhecem

Expressão
Parênteses
aninhados

(((?1)*))1

"Squares"

(.*)1

an b n

(a(?1)?b)1
1

sintaxe do Perl para recursive capture buffers
Match de regexps com
backreferences é um
problema NP-completo.
P vs NP
De novo essa #&$%@?
*assumindo que P!=NP

NP-HARD

NP-COMPLETE
NP

P
Para provar NP-completude
Eu contaria uma piada sobre NP-completos, mas se você
já ouviu uma, já conhece todas.
Provar pertinência em NP-hard
NP-HARD

Reduzir um problema NP-completo (3SAT, coloração de grafos, etc.) ao
problema em questão.

NP-COMPLETE

Provar pertinência em NP
NP

P

Provar que é possível verificar respostas
positivas às instâncias do problema em
tempo polinomial.
3-SAT
Um problema NP-completo

(¬x1
( x1
( x1
( x2
(¬x1
( x1
(¬x1

∨
∨
∨
∨
∨
∨
∨

x2
¬x3
¬x2
¬x3
x3
x2
¬x2

∨
∨
∨
∨
∨
∨
∨

x4)
x4)
¬x4)
¬x4)
¬x4)
x3)
¬x3)

∧
∧
∧
∧
∧
∧
3-SAT
Reduzindo a expressões regulares (com backreferences)
3-SAT com Regexp
variáveis x1, x2, x3 e x4
(¬x1 ∨

^(x?)(x?)(x?)(x?).*;

x2 ∨

x4) ∧

(x1|2|4),

( x1 ∨ ¬x3 ∨

x4) ∧

(1|x3|4),

( x1 ∨ ¬x2 ∨ ¬x4) ∧

(1|x2|x4),

( x2 ∨ ¬x3 ∨ ¬x4) ∧

(2|x3|x4),

(¬x1 ∨

x3 ∨ ¬x4) ∧

(x1|3|x4),

( x1 ∨

x2 ∨

x3) ∧

(¬x1 ∨ ¬x2 ∨ ¬x3)

(1|2|3),
(x1|x2|x3),$
match 'xxxx;x,x,x,x,x,x,x,'
Conclusão
● Match de expressões regulares com backreferences
é um problema NP-completo.
● É possível reconhecer cadeias em linguagens
regulares com algoritmo polinomial.
● Implementações como a da JDK podem levar a
tempos de execução exponenciais mesmo com
expressões que denotam linguagens regulares.
● O uso de expressões regulares modernas pode levar
a falhas de segurança em aplicações online.

Mais conteúdo relacionado

Destaque

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Destaque (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Logs de aplicação: exemplos de informações

  • 1.
  • 2. O que há de errado com expressões regulares? *elas são NP-completas, só que não. juanlopes.net/devday2013
  • 3. Logs de aplicação Contém muita informação 186.247.10.187 - - GET /gnews/gnews_600/gnews_1374508780437_1374508780437_1470.ts HTTP/1.1 "200" 346672 "-" 0.232 "AppleCoreMedia/1.0.0.10B329 (iPad; U; CPU OS 6_1_3 like Mac OS X; pt_br)" "-" - [MISS] 0.006 ms 201.51.232.169 - - GET /gnews/gnews_1000/gnews_1374508779820_1374508779820_1466.ts HTTP/1.1 "200" 552156 "http://globotv.globo.com/globo-news/globo-news-ao-vivo/v/globonewsao-vivo/61910/" 0.480 "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36" "-" - [MISS] 0.008 ms 201.7.186.60 - - GET /ber2/ber2_400/playlist.m3u8 HTTP/1.1 "200" 538 "http: //g1.globo.com/jornal-hoje/ao-vivo.html" 0.001 "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36" "-" - [EXPIRED] 0.001 ms
  • 4. Logs de aplicação Exemplo: IP de origem 186.247.10.187 - - GET /gnews/gnews_600/gnews_1374508780437_1374508780437_1470.ts HTTP/1.1 "200" 346672 "-" 0.232 "AppleCoreMedia/1.0.0.10B329 (iPad; U; CPU OS 6_1_3 like Mac OS X; pt_br)" "-" - [MISS] 0.006 ms 201.51.232.169 - - GET /gnews/gnews_1000/gnews_1374508779820_1374508779820_1466.ts HTTP/1.1 "200" 552156 "http://globotv.globo.com/globo-news/globo-news-ao-vivo/v/globonewsao-vivo/61910/" 0.480 "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36" "-" - [MISS] 0.008 ms 201.7.186.60 - - GET /ber2/ber2_400/playlist.m3u8 HTTP/1.1 "200" 538 "http: //g1.globo.com/jornal-hoje/ao-vivo.html" 0.001 "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36" "-" - [EXPIRED] 0.001 ms
  • 5. Logs de aplicação Exemplo: identificador do vídeo 186.247.10.187 - - GET /gnews/gnews_600/gnews_1374508780437_1374508780437_1470.ts HTTP/1.1 "200" 346672 "-" 0.232 "AppleCoreMedia/1.0.0.10B329 (iPad; U; CPU OS 6_1_3 like Mac OS X; pt_br)" "-" - [MISS] 0.006 ms 201.51.232.169 - - GET /gnews/gnews_1000/gnews_1374508779820_1374508779820_1466.ts HTTP/1.1 "200" 552156 "http://globotv.globo.com/globo-news/globo-news-ao-vivo/v/globonewsao-vivo/61910/" 0.480 "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36" "-" - [MISS] 0.008 ms 201.7.186.60 - - GET /ber2/ber2_400/playlist.m3u8 HTTP/1.1 "200" 538 "http: //g1.globo.com/jornal-hoje/ao-vivo.html" 0.001 "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36" "-" - [EXPIRED] 0.001 ms
  • 6. Logs de aplicação Exemplo: URL da página em que o vídeo foi reproduzido 186.247.10.187 - - GET /gnews/gnews_600/gnews_1374508780437_1374508780437_1470.ts HTTP/1.1 "200" 346672 "-" 0.232 "AppleCoreMedia/1.0.0.10B329 (iPad; U; CPU OS 6_1_3 like Mac OS X; pt_br)" "-" - [MISS] 0.006 ms 201.51.232.169 - - GET /gnews/gnews_1000/gnews_1374508779820_1374508779820_1466.ts HTTP/1.1 "200" 552156 "http://globotv.globo.com/globo-news/globo-news-ao-vivo/v/globonewsao-vivo/61910/" 0.480 "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36" "-" - [MISS] 0.008 ms 201.7.186.60 - - GET /ber2/ber2_400/playlist.m3u8 HTTP/1.1 "200" 538 "http: //g1.globo.com/jornal-hoje/ao-vivo.html" 0.001 "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36" "-" - [EXPIRED] 0.001 ms
  • 7. Expressões regulares Para extrair estas informações (?<ip>[d.]+)s-s-sGETs(?<path>/?(? <stream>[^/]*)/?[^.]*.?(?<extension> [^s?]*))(?<querystring>[^s]*)s[^s]*s" (?<status>d*)"s(?<body_bytes_sent>[d]*) s"(?<http_referer>[^"]*)"s[d.]+s"(? <user_agent>[^"]*)"s"(?<forwarded_for>[^"] *)"s-s[(?<cache_status>[w-]*)]s(? <upstream_response_time>[^s]*)sms.*
  • 8. Benchmarks são limitados Essa palestra é basicamente para dizer o óbvio sljit.sourceforge.net/regex_perf.html
  • 9. Russ Cox Um dos maiores committers da linguagem Go “RE2, provides most of the functionality of PCRE using a C++ interface very close to PCRE's, but it guarantees linear time execution and a fixed stack footprint. RE2 is now in widespread use at Google, both in Code Search and in internal systems like Sawzall and Bigtable”
  • 11. Complexidade de algoritmos Como medir a complexidade de: (?<ip>[d.]+)s-s-sGETs(?<path>/?(?<stream>[^/]*)/?[^.]*.?(?<extension>[^s?]*)) (?<querystring>[^s]*)s[^s]*s"(?<status>d*)"s(?<body_bytes_sent>[d]*)s"(? <http_referer>[^"]*)"s[d.]+s"(?<user_agent>[^"]*)"s"(?<forwarded_for>[^"]*)"s-s [(?<cache_status>[w-]*)]s(?<upstream_response_time>[^s]*)sms.*
  • 12. Repositórios online Não estão livres de regexes maliciosas
  • 14. Acontece nos melhores projetos Mas não deveria
  • 15. Regex: (a?a)+b Regexes não deveriam se comportar assim:
  • 17. Expressões regulares em tempo linear? SIM e NÃO?!
  • 18. Expressões regulares em tempo linear? SIM e NÃO?!
  • 19. Woody Allen Noam Chomsky Pai da linguística moderna (e um ativista barulhento) “A generative grammar must be a system of rules that can iterate to generate an indefinitely large number of structures.”
  • 20. Hierarquia de Chomsky Essencial para a teoria de linguagens de programação IRRESTRITAS SENSÍVEIS AO CONTEXTO LIVRES DE CONTEXTO REGULARES
  • 21. Hierarquia de Chomsky Cada gramática exige uma máquina para reconhecê-la Gramática Autômato Regras 0 Irrestrita Máquina de Turing α→β 1 Sensível ao contexto Autômato linearmente limitado αSβ → αγβ 2 Livre de contexto Autômato de pilha S→γ Autômato finito S→ε S→a S → aT 3 Regular
  • 22. Expressões regulares Denotam linguagens, hum…, regulares. Forma Descrição ER1 ∅ Linguagem vazia ER2 ε Linguagem contendo apenas cadeia vazia ER3 a Linguagem contendo apenas cadeia a ER4 α|β União entre Lα e Lβ ER5 αβ Concatenação entre Lα e Lβ ER6 α* Fecho Kleene sobre Lα
  • 23. Autômatos finitos Reconhecem linguagens regulares abc?d a b c d ε ε abcd* a b c d ε
  • 24. Uma notação simplificada Para representar autômatos finitos Autômato a ε Notação a Instrução CONSUME JUMP MATCH
  • 25. Uma notação simplificada Mesmos exemplos em nova notação abc?d a b c d abcd* a b c d
  • 26. Conversão Expressão regular → autômato finito Expressão Autômato a a αβ α β α|β α α? α α+ α* α α β
  • 27. Conversão Útil para representar o autômato de diversas formas ER abc?d abcd+ (a?a)+b Autômato a a b b a c c a d d b Array Instruções 'a', 'b', [1, 2], 'c', 'd' 0000: 0001: 0002: 0003: 0004: 0005: CONSUME 'a' CONSUME 'b' JUMP (1, 2) CONSUME 'c' CONSUME 'd' MATCH! 'a', 'b', 'c', 'd', [1, -1] 0000: 0001: 0002: 0003: 0004: 0005: CONSUME a CONSUME b CONSUME c CONSUME d JUMP (1, -1) MATCH! [1, 2], 'a', 'a', [1, -3], 'b' 0000: 0001: 0002: 0003: 0004: 0005: JUMP (1, 2) CONSUME a CONSUME a JUMP (1, -3) CONSUME b MATCH!
  • 28. NFA: Autômato Finito Não Determinístico c INDETERMINISMO d
  • 29. Indeterminismo Potencial exponencial devastador, em alguns casos Expressão (a?a)+b Autômato a 0000: 0001: 0002: 0003: 0004: 0005: a Array b [1, 2], 'a', 'a', [1, -3], 'b' JUMP (1, 2) CONSUME 'a' CONSUME 'a' JUMP (1, -3) CONSUME 'b' MATCH!
  • 33. Simular autômato Várias formas, com vantagens e desvantagens Método Vantagem Desvantagem Backtracking Implementação simples Simulação exponencial Backtracking com memorização Implementação simples; complexidade polinomial Chamadas recursivas; acesso aleatório à entrada Converter para DFA Simulação linear Conversão exponencial Simulação paralela Sem chamadas recursivas; acesso sequencial à entrada Simulação superlinear Conversão preguiçosa para DFA Boa localidade de referência; melhor caso linear Pior caso ainda superlinear
  • 34. Simular autômato Paralela: melhor custo/benefício Método Vantagem Desvantagem Backtracking Implementação simples Simulação exponencial Backtracking com memorização Implementação simples; complexidade polinomial Chamadas recursivas; acesso aleatório à entrada Converter para DFA Simulação linear Conversão exponencial Simulação paralela Sem chamadas recursivas; acesso sequencial à entrada Simulação superlinear Conversão preguiçosa para DFA Boa localidade de referência; melhor caso linear Pior caso ainda superlinear
  • 35. PyRex O código cabe num slide o/
  • 36. Benchmarks: (a?a)+b Caso O(2^n): exponencialmente melhor
  • 37. Benchmarks: a*b Caso O(n): pior por um fator constante
  • 38. Benchmarks: a*a*a*a*a*b Caso O(n^5): polinomialmente melhor (e Ruby rouba)
  • 39. Expressões regulares em tempo linear? SIM e NÃO?!
  • 40. Linguagens não-regulares O que elas tem a ver com expressões regulares? IRRESTRITAS SENSÍVEIS AO CONTEXTO LIVRES DE CONTEXTO REGULARES
  • 41. Linguagens não-regulares Alguns exemplos Exemplos Parênteses aninhados (()()(())), (((()))), ... "Squares" DogDog, CatCat, WikiWiki, ... an b n ab, aabb, aaabbb, ...
  • 42. Linguagens não-regulares Alguns exemplos IRRESTRITAS SENSÍVEIS AO CONTEXTO anbncn, "squares" LIVRES DE CONTEXTO anbn, parênteses REGULARES
  • 43. Linguagens não-regulares Expressões regulares que as reconhecem Expressão Parênteses aninhados (((?1)*))1 "Squares" (.*)1 an b n (a(?1)?b)1 1 sintaxe do Perl para recursive capture buffers
  • 44. Match de regexps com backreferences é um problema NP-completo.
  • 45. P vs NP De novo essa #&$%@? *assumindo que P!=NP NP-HARD NP-COMPLETE NP P
  • 46. Para provar NP-completude Eu contaria uma piada sobre NP-completos, mas se você já ouviu uma, já conhece todas. Provar pertinência em NP-hard NP-HARD Reduzir um problema NP-completo (3SAT, coloração de grafos, etc.) ao problema em questão. NP-COMPLETE Provar pertinência em NP NP P Provar que é possível verificar respostas positivas às instâncias do problema em tempo polinomial.
  • 47. 3-SAT Um problema NP-completo (¬x1 ( x1 ( x1 ( x2 (¬x1 ( x1 (¬x1 ∨ ∨ ∨ ∨ ∨ ∨ ∨ x2 ¬x3 ¬x2 ¬x3 x3 x2 ¬x2 ∨ ∨ ∨ ∨ ∨ ∨ ∨ x4) x4) ¬x4) ¬x4) ¬x4) x3) ¬x3) ∧ ∧ ∧ ∧ ∧ ∧
  • 48. 3-SAT Reduzindo a expressões regulares (com backreferences) 3-SAT com Regexp variáveis x1, x2, x3 e x4 (¬x1 ∨ ^(x?)(x?)(x?)(x?).*; x2 ∨ x4) ∧ (x1|2|4), ( x1 ∨ ¬x3 ∨ x4) ∧ (1|x3|4), ( x1 ∨ ¬x2 ∨ ¬x4) ∧ (1|x2|x4), ( x2 ∨ ¬x3 ∨ ¬x4) ∧ (2|x3|x4), (¬x1 ∨ x3 ∨ ¬x4) ∧ (x1|3|x4), ( x1 ∨ x2 ∨ x3) ∧ (¬x1 ∨ ¬x2 ∨ ¬x3) (1|2|3), (x1|x2|x3),$ match 'xxxx;x,x,x,x,x,x,x,'
  • 49. Conclusão ● Match de expressões regulares com backreferences é um problema NP-completo. ● É possível reconhecer cadeias em linguagens regulares com algoritmo polinomial. ● Implementações como a da JDK podem levar a tempos de execução exponenciais mesmo com expressões que denotam linguagens regulares. ● O uso de expressões regulares modernas pode levar a falhas de segurança em aplicações online.