devday2013

Juan Lopes
Juan LopesSoftware developer at Intelie
devday2013
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.
1 of 49

Recommended

20150917 expressoes regulares by
20150917 expressoes regulares20150917 expressoes regulares
20150917 expressoes regularesGabriell Nascimento
476 views31 slides
qconrio2015 by
qconrio2015qconrio2015
qconrio2015Juan Lopes
684 views68 slides
qconsp2015 by
qconsp2015qconsp2015
qconsp2015Juan Lopes
1.4K views67 slides
PIPES: Uma linguagem para processamento distribuído de eventos complexos by
PIPES: Uma linguagem para processamento distribuído de eventos complexosPIPES: Uma linguagem para processamento distribuído de eventos complexos
PIPES: Uma linguagem para processamento distribuído de eventos complexosJuan Lopes
1.5K views82 slides
dnarj20130504 by
dnarj20130504dnarj20130504
dnarj20130504Juan Lopes
1.5K views41 slides
uerj201212 by
uerj201212uerj201212
uerj201212Juan Lopes
447 views71 slides

More Related Content

Featured

ChatGPT and the Future of Work - Clark Boyd by
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
24.3K views69 slides
Getting into the tech field. what next by
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
5.7K views22 slides
Google's Just Not That Into You: Understanding Core Updates & Search Intent by
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
6.4K views99 slides
How to have difficult conversations by
How to have difficult conversations How to have difficult conversations
How to have difficult conversations Rajiv Jayarajah, MAppComm, ACC
5K views19 slides
Introduction to Data Science by
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data ScienceChristy Abraham Joy
82.3K views51 slides
Time Management & Productivity - Best Practices by
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
169.7K views42 slides

Featured(20)

ChatGPT and the Future of Work - Clark Boyd by 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 Boyd24.3K views
Getting into the tech field. what next by Tessa Mero
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
Tessa Mero5.7K views
Google's Just Not That Into You: Understanding Core Updates & Search Intent by Lily Ray
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
Lily Ray6.4K views
Time Management & Productivity - Best Practices by Vit Horky
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
Vit Horky169.7K views
The six step guide to practical project management by MindGenius
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
MindGenius36.6K views
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright... by RachelPearson36
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...
RachelPearson3612.7K views
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present... by Applitools
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Applitools55.5K views
12 Ways to Increase Your Influence at Work by GetSmarter
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
GetSmarter401.7K views
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G... by DevGAMM Conference
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
DevGAMM Conference3.6K views
Barbie - Brand Strategy Presentation by Erica Santiago
Barbie - Brand Strategy PresentationBarbie - Brand Strategy Presentation
Barbie - Brand Strategy Presentation
Erica Santiago25.1K views
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them well by Saba Software
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them wellGood Stuff Happens in 1:1 Meetings: Why you need them and how to do them well
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them well
Saba Software25.2K views
Introduction to C Programming Language by Simplilearn
Introduction to C Programming LanguageIntroduction to C Programming Language
Introduction to C Programming Language
Simplilearn8.4K views
The Pixar Way: 37 Quotes on Developing and Maintaining a Creative Company (fr... by Palo Alto Software
The Pixar Way: 37 Quotes on Developing and Maintaining a Creative Company (fr...The Pixar Way: 37 Quotes on Developing and Maintaining a Creative Company (fr...
The Pixar Way: 37 Quotes on Developing and Maintaining a Creative Company (fr...
Palo Alto Software88.4K views
9 Tips for a Work-free Vacation by Weekdone.com
9 Tips for a Work-free Vacation9 Tips for a Work-free Vacation
9 Tips for a Work-free Vacation
Weekdone.com7.2K views
How to Map Your Future by SlideShop.com
How to Map Your FutureHow to Map Your Future
How to Map Your Future
SlideShop.com275.1K views

devday2013

  • 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.