-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathregex.tex
More file actions
710 lines (503 loc) · 22 KB
/
regex.tex
File metadata and controls
710 lines (503 loc) · 22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
% vim: autowrite
\documentclass[10pt, a4paper, landscape]{scrartcl}
\usepackage{cheatsheet} % See cheatsheet.sty
\usepackage{nimbusmononarrow} % Required for tt font type
\usepackage[utf8]{inputenc} % Required for inputting international characters
\usepackage[T1]{fontenc} % Output font encoding for international characters
\usepackage{graphicx} % Required for including images
\usepackage{fdsymbol} % Required for some math symbols, like \lAngle
\usepackage[dvipsnames]{xcolor} % Required for source-highlight coloured output
\usepackage{textcomp} % Required for \textquotesingle
\usepackage{listings} % Required for inserting code snippets
\definecolor{DarkGreen}{rgb}{0.0,0.4,0.0} % Comment color
\definecolor{highlight}{RGB}{255,251,204} % Code highlight color
\lstloadlanguages{Perl,Java,[Sharp]C,Python,bash}
\lstdefinestyle{SourceCode}{%
backgroundcolor=\color{highlight},
basicstyle=\footnotesize\ttfamily,
breakatwhitespace=false,
breaklines=true, % Automatic line breaking (prevents code from protruding outside the box)
captionpos=b,
commentstyle=\color{DarkGreen}, % Style of comments within the code
deletekeywords={}, % If you want to delete any keywords from the current language separate them by commas
%escapeinside={\%}, % This allows you to escape to LaTeX using the character in the bracket
firstnumber=1, % Line numbers begin at line 1
frame=single, % Frame around the code box, value can be: none, leftline, topline, bottomline, lines, single, shadowbox
frameround=tttt, % Rounds the corners of the frame for the top left, top right, bottom left and bottom right positions
keywordstyle=\color{Blue}\bf, % Functions are bold and blue
morekeywords={}, % Add any functions no included by default here separated by commas
numbers=none, % Location of line numbers, can take the values of: none, left, right
numbersep=10pt, % Distance of line numbers from the code box
numberstyle=\tiny\color{Gray}, % Style used for line numbers
rulecolor=\color{black}, % Frame border color
showstringspaces=false, % Don't put marks in string spaces
showtabs=false, % Display tabs in the code as lines
stepnumber=5, % The step distance between line numbers, i.e. how often will lines be numbered
stringstyle=\color{Purple}, % Strings are purple
tabsize=2, % Number of spaces per tab in the code
}
\lstdefinestyle{Perl}{language=Perl,style=SourceCode}
\lstdefinestyle{Java}{language=Perl,style=SourceCode,morecomment=[l]{//}}
\lstdefinestyle{CSharp}{language=[Sharp]C,style=SourceCode}
\lstdefinestyle{Python}{language=Python,style=SourceCode}
\lstdefinestyle{Bash}{language=bash,style=SourceCode,morekeywords={perl}}
\lstdefinestyle{RegEx}{language={},style=SourceCode,backgroundcolor=\color{gray!30},rulecolor=\color{gray!30},frameround=ffff}
\usepackage[% This block contains information used to annotate the PDF
colorlinks=true,
urlcolor=blue,
pdftitle={Regular Expressions},
pdfauthor={Gastón Simone},
pdfsubject={Regular Expressions cheatsheet},
pdfkeywords={Regular Expressions, Cheatsheet}
]{hyperref}
\renewcommand{\familydefault}{\sfdefault} % Use sans-serif fond as bodytext family font
\renewcommand{\sfdefault}{phv} % Use Helvetica as sans-serif font
\renewcommand{\ttdefault}{pcr} % Use Courier as mono-spaced font
\newcommand{\regex}[1]{\texttt{#1}}
\newcommand{\cregex}[1]{\colorbox{gray!30}{\small\regex{#1}}}
\renewcommand{\cmdleft}[1]{\cregex{#1}}
\newcommand{\code}[1]{\texttt{#1}}
\newcommand{\bs}{\textbackslash}
\newcommand{\re}{\textit{re}}
\newcommand{\dnet}{{.}Net}
\newcommand{\insertcode}[2]{\lstinputlisting[label=#2,style=#1]{#2}}
\newcommand{\reshortexample}[1]{\cregex{\input{#1}}}
\newcommand{\relongexample}[1]{\lstinputlisting[label=#1,style=RegEx]{./regex_examples/#1}}
\newcommand{\equivalence}[2]{\cmdleft{#1}=\cmdleft{#2}\\}
\newcommand{\equivcomment}[3]{\cmdleft{#1}=\cmdleft{#2}\dotfill{}~\cmdright{#3}\\}
\begin{document}
\begin{cheatsheet}{Regular Expressions Basics}
\begin{col1}
\re\ = \emph{regular expression}.\\
\emph{greedy} = always favour matching\\
\emph{lazy} = always favour not matching
\sectiontitle{Any character}
\command{.}{(dot) Any character, except new line}
\command{\bs.}{Literal dot}
\sectiontitle{Character classes (custom)}
\command{[\dots]}{Any character listed}
\command{[\^{}\dots]}{Any character \emph{not} listed}
\command{[a-z]}{Range, any character from a to z}
\command{[-\dots]}{To include dash (-), add it first}
\sectiontitle{Boundaries}
\command{\^{}, \$}{[Start, End] of line}
\command{\bs{}A, \bs{}Z, \bs{}z}{[Start, End, End] of string}
The difference between these occurs in multi-line mode.\\
\command{\bs{}b}{Word boundary (Perl, Java, \dnet)}
\command{\bs{}B}{Not word boundary}
\command{\bs{}<,\bs{}>}{[Start, End] of word\textsuperscript{$\dagger$} (Vim)}
\command{\bs{}G}{Match starts where the previous match ended}
\command{\bs{}Q\emph{text}\bs{}E}{Literal \emph{text} inside regex}
$\dagger$ Perl/Java/\dnet:\\
\mbox{}\ \ \ \ \cregex{\bs{}<} $\to$ \cregex{(?<!\bs{}w)(?=\bs{}w)}\\
\mbox{}\ \ \ \ \cregex{\bs{}>} $\to$ \cregex{(?<=\bs{}w)(?!\bs{}w)}\\
(see \emph{Lookaround} in next page).
\end{col1}
\begin{col2}
\sectiontitle{Grouping and Backreferences}
\command{(\re)}{Group \re\ as a unit (Perl, Java, \dnet)}
\command{\bs(\re\bs)}{Vim without \emph{very magic}}
\command{\bs1,\dots,\bs9}{$[1..9]$-th matched \regex{()}}
\sectiontitle{Substitutions}
\command{\$1,\dots,\$9}{$[1..9]$-th matched \regex{()}}
\command{\$+}{Last matched \regex{()}}
\command{\$\&, \&}{Entire matched string (Perl, Vim)}
\command{\$\`{}, \$\textquotesingle{}}{Text [before, after] match}
\command{\$\_}{Entire input text}
\sectiontitle{Quantifiers (greedy)}
(Perl/Java/\dnet, Vim without \emph{very magic}):\\
\command{\re?, \re\bs?}{\re\ optional (0 or 1)}
\command{\re*}{Any quantity of \re\ (0 or more)}
\command{\re+, \re\bs+}{At least one of \re\ (1 or more)}
\command{\re\{n\}, \re\bs\{n\}}{\re\ exactly $n$ times}
\command{\re\{n,\}, \re\bs\{n,\}}{\re\ at least $n$ times}
\command{\re\{n,m\}, \re\bs\{n,m\}}{\re\ at least $n$ and at most $m$ times}
\sectiontitle{Quantifiers (lazy)}
(Perl/Java/\dnet, Vim without \emph{very magic}):\\
\command{\re??, \re\bs\{-,1\}}{\re\ optional (0 or 1)}
\command{\re*?, \re\bs\{-\}}{Any quantity of \re\ (0 or more)}
\command{\re+?, \re\bs\{-1,\}}{At least one of \re\ (1 or more)}
\command{\re\{n\}?, \re\bs\{-n\}}{\re\ exactly $n$ times}
\command{\re\{n,\}?, \re\bs\{-n,\}}{\re\ at least $n$ times}
\command{\re\{n,m\}?, \re\bs\{-n,m\}}{\re\ between $n$ and $m$ times}
\end{col2}
\begin{col3}
\sectiontitle{Alternation (branching)}
\command{\re|\re}{\re\ or \re\ (Perl/Java/\dnet)}
\command{\re\bs|\re}{\re\ or \re\ (Vim without \emph{very magic})}
\emph{Note:} In NFA engines alternatives are tried in order of appearance. So
placing them in probability order prevents backtracking, improving
efficiency.\\
\sectiontitle{Shorthands}
\command{\bs{}s}{White space (space, tab, etc.)\textsuperscript{$\dagger$}}
\command{\bs{}S}{Not \cregex{\bs{}s}}
\command{\bs{}d}{Digit (\cregex{[0-9]})\textsuperscript{$\dagger$}}
\command{\bs{}D}{Not \cregex{\bs{}d}}
\command{\bs{}w}{Word char (\cregex{[a-zA-Z0-9\_]})\textsuperscript{$\dagger$}}
\command{\bs{}W}{Not \cregex{\bs{}w}}
\command{\bs{}t, \bs{}n}{Tab, New line}
\begin{cheatnote}
$\dagger$ Some flavours also recognise special Unicode characters in the same character group.\\
In Vim \cregex{\bs\_s} also includes new line.\\
\end{cheatnote}
\sectiontitle{Modes and Flags}
\command{i}{Ignore case\textsuperscript{$\dagger$} (Perl/Vim)}
\command{m}{Multi-line mode (Perl)}
\command{s}{Dot matches new line\textsuperscript{$\ddagger$} (Perl)}
\command{x}{Ignore white space\textsuperscript{\textsection} (Perl)}
\command{g}{Apply substitution in all occurrences (Perl/Vim)}
\begin{cheatnote}
$\dagger$ Java: \code{Pattern.CASE\_INSENSITIVE},\\
\dnet: \code{RegexOptions.IgnoreCase}.
\end{cheatnote}
$\ddagger$ In Vim, use \cregex{\bs\_.} to make dot match new lines.\\
\begin{cheatnote}
\textsection\ Java: \code{Pattern.COMMENTS},\\
\dnet: \code{RegexOptions.IgnorePatternWhiteSpace}.
\end{cheatnote}
\end{col3}
\end{cheatsheet}
\newpage
\begin{cheatsheet}{Regular Expressions Advanced}
\begin{col1}
\sectiontitle{Lookaround}
\emph{Lookahead} = Check if \re\ matches at current position, but do not consume.\\
\emph{Lookbehind} = Check if \re\ matches just before what follows, but do not consume.\\
\emph{Negative} = Check if \re\ does \emph{not} match.\\
(Perl/Java/\dnet, Vim):\\
\command{(?=\re), \re\bs{}@=}{Lookahead}
\command{(?!\re), \re\bs{}@!}{Negative lookahead}
\command{(?<=\re), \re\bs{}@<=}{Lookbehind}
\command{(?<!\re), \re\bs{}@<!}{Negative lookbehind}
\sectiontitle{Non-capturing parentheses and comments}
Group as a unit, but do not capture for backreferencing.\\
\command{(?:\re)}{Perl, Java, \dnet}
\command{\bs\%(\re\bs)}{Vim}
\command{(?\#\emph{free text})}{Comment inside regex}
\sectiontitle{Branch reset}
\command{(?|\re)}{Restart group numbering for each branch in \re}
Not available in Vim.\\
\end{col1}
\begin{col2}
\sectiontitle{Named captures}
\command{(?<\emph{name}>\re)}{Capture \re\ under \emph{name}}
\command{\bs{}k<\emph{name}>}{Named backreference}
\command{\$+\{\emph{name}\}}{Named substitution (Perl)}
\command{\$\{\emph{name}\}}{Named substitution (\dnet)}
Not available in Vim.\\
\sectiontitle{Atomic grouping}
Match \re\ without retry. In a NFA engine, discard all the possible backtracking
states for the enclosed \re.\\
\command{(?>\re)}{Perl/Java/\dnet}
\command{\re\bs{}@>}{Vim}
\sectiontitle{Possessive quantifiers}
\command{\re?+}{\cregex{(?>\re?)}}
\command{\re*+}{\cregex{(?>\re*)}}
\command{\re++}{\cregex{(?>\re+)}}
\command{\re\{n,m\}+}{\cregex{(?>\re\{n,m\})}}
Not available in Vim (but can be done with atomic grouping).\\
\sectiontitle{End of previous match}
\command{\bs{}G}{Matches where the previous match ended}
Useful when using the \regex{g} mode.\\
In Perl, use \code{pos(\$str)} to know the current location where
\regex{\bs{}G} would match in \code{\$str}.\\
Not available in Vim.
\end{col2}
\begin{col3}
\sectiontitle{Conditional expressions}
If \emph{cond} then \re1, else \re2. \re2 is optional.\\
Perl/Java/\dnet:\\
\command{(?(\emph{cond})\re)}{Without \emph{else} \re}
\command{(?(\emph{cond})\re1|\re2)}{With \emph{else} \re}
\command{(?(\emph{n})$\cdots$)}{\emph{cond} = $n$-th \regex{()} matched}
\emph{cond} can be a \emph{lookaround} expression (see the examples).\\
Not available in Vim.\\
\sectiontitle{Dynamic regex and embedded code}
\command{(??\{\emph{code}\})}{Match \re\ built by \emph{code} here}
\command{(?\{\emph{code}\})}{\emph{code} that does anything}
Useful for debugging regex by \texttt{print}ing.\\
Not available in Vim.\\
\sectiontitle{Recursive expressions}
\command{(?R)}{Repeat entire \re\ here}
\command{(?R\emph{n})}{Repeat \re\ captured under group $n$ here}
Not available in Vim.\\
\sectiontitle{Mode modifiers}
(Perl/Java/\dnet, Vim):\\
\command{(?i), \bs{}c}{Turn case-insensitive on}
\command{(?-i), \bs{}C}{Turn case-insensitive off}
\command{(?i:\re)}{Be case insensitive for \re}
\end{col3}
\end{cheatsheet}
\newpage
\begin{cheatsheet}{Regular Expressions and Characters}
\begin{col1}
\sectiontitle{Unicode properties}
Perl/Java/\dnet:\\
\command{\bs{}p\{L\}}{Letters}
\command{\bs{}p\{M\}}{Accent marks, etc.}
\command{\bs{}p\{Z\}}{Spaces, etc.}
\command{\bs{}p\{S\}}{Dingbats and symbols}
\command{\bs{}p\{N\}}{Numeric characters}
\command{\bs{}p\{P\}}{Punctuation characters}
\command{\bs{}p\{C\}}{Everything else}
\sectiontitle{Unicode sub-properties}
\command{\bs{}p\{Ll\}}{Lower-case letters}
\command{\bs{}p\{Lu\}}{Upper-case letters}
\command{\bs{}p\{Mn\}}{Non-spacing mark (accents, \dots)}
\command{\bs{}p\{Sm\}}{Math symbol ($-$,$+$,$\div$,$\leq$,\dots)}
\command{\bs{}p\{Sc\}}{Currency symbol (\textyen,\textcent,\texteuro,\textdollar,\textsterling,\dots)}
\command{\bs{}p\{Nd\}}{Decimal digit}
\command{\bs{}p\{Nl\}}{Letter number (mostly Roman numerals)}
\command{\bs{}p\{Pd\}}{Dash punctuation}
\command{\bs{}p\{Ps\}}{Open punctuation ([, \{, $\lAngle$, \dots)}
\command{\bs{}p\{Pe\}}{Close punctuation (], \}, $\rAngle$, \dots)}
\command{\bs{}p\{Cc\}}{ASCII and Latin-1 control characters (\texttt{TAB}, \texttt{CR}, \texttt{LF}, \dots)}
\sectiontitle{Unicode negated properties}
\command{\bs{}P\{$\cdots$\}}{Perl/Java/\dnet}
\command{\bs{}p\{\^{}$\cdots$\}}{Perl}
\end{col1}
\begin{col2}
\sectiontitle{Unicode blocks and scripts}
\command{\bs{}p\{InCyrillic\}}{Cyrillic character (Perl, Java)}
\command{\bs{}p\{IsCyrillic\}}{Cyrillic character (\dnet)}
\command{\bs{}p\{Latin\}}{Latin character}
\command{\bs{}p\{Greek\}}{Greek character}
\command{\bs{}p\{Hebrew\}}{Hebrew character}
\sectiontitle{POSIX character classes}
\command{[:alnum:]}{Alphanumeric characters}
\command{[:alpha:]}{Alphabetic characters}
\command{[:blank:]}{Space and tab}
\command{[:cntrl:]}{Control characters}
\command{[:digit:]}{Numeric characters}
\command{[:graph:]}{Non-blank characters}
\command{[:lower:]}{Lower-case alphabetic characters}
\command{[:print:]}{\cregex{[:graph:]} and the space character}
\command{[:punct:]}{Punctuation characters}
\command{[:space:]}{All whitespace characters}
\command{[:upper:]}{Upper-case alphabetic characters}
\command{[:xdigit:]}{Hexadecimal digits (\cregex{[0-9a-fA-F]})}
\sectiontitle{POSIX collating sequences}
\command{[.span-ll.]}{Match ``ll'' as single character}
\command{[.ch.]}{Match ``ch'' as single character}
\command{[.eszet.]}{Match ``ss'' (``ß'') as single character}
\sectiontitle{POSIX character equivalents}
\command{[[=a=][=n=]]}{Character \emph{equivalents} for \emph{a} and \emph{n} (a, á, à, ä, \dots, n, ñ, \dots)}
\end{col2}
\begin{col3}
\sectiontitle{Special characters and other shorthands}
\command{\bs\textit{char}}{Literal \textit{char}}
\command{\bs{}t}{Tab (\texttt{HT, TAB})}
\command{\bs{}n}{New line (\texttt{LF, NL})}
\command{\bs{}r}{Carriage return (\texttt{CR})}
\command{\bs{}f}{Form feed (\texttt{FF})}
\command{\bs{}a}{Alarm (\texttt{BEL})}
\command{\bs{}e}{Escape (think troff) (\texttt{ESC})}
\command{\$\$}{Literal \$ (\dnet)}
\command{\bs{}l}{Lower-case next char}
\command{\bs{}u}{Upper-case next char}
\command{\bs{}L\emph{text}\bs{}E}{Lower-case \emph{text}}
\command{\bs{}U\emph{text}\bs{}E}{Upper-case \emph{text}}
\command{\bs\emph{num}}{Octal escape}
\command{\bs{}x\emph{num}, \bs{}x\{\emph{num}\}}{Hex escape}
\command{\bs{}u\emph{num}, \bs{}U\emph{num}}{Unicode escape}
\command{\bs{}c\emph{x}, \bs{}c\emph{X}}{\texttt{CTRL-\emph{X}}}
\command{\bs{}N\{\emph{U+263D}\}}{Unicode character}
\command{\bs{}N\{\emph{name}\}}{Character by Unicode \emph{name}}
\sectiontitle{Class set operations}
\command{[[a-z]\&\&[\^{}aeiou]]}{Class 1 except class 2 (Java)}
\command{[[a-z]-[aeiou]]}{Class 1 except class 2 (\dnet)}
\end{col3}
\end{cheatsheet}
\newpage
\begin{cheatsheet}{Regular Expressions Efficiency}
\begin{col1}
Notation: $worse\to better$
\sectiontitle{General guidelines}
\begin{itemize}
\item Avoid recompiling the \re.
\item Use non-capturing parentheses (but check they are indeed faster in
your case!).
\item Split into multiple \re's (or literal text search) if
it can make the process faster.
\item Use leading anchors (\cregex{\^{}}, \cregex{\bs{}A}, \cregex{\$},
\cregex{\bs{}Z}, etc.) to reduce the number of locations where the
\re{} is evaluated.
\item Use atomic grouping and possessive quantifiers to avoid unnecessary
backtracking (especially important in non-matching cases).
\item Put the most-likely alternatives first (only affects traditional NFA
engines).
\end{itemize}
\sectiontitle{Lazy quantifiers may be slower than greedy}
Because they must jump between checking what the quantifier controls with
checking what comes after. Example: \cregex{"(.*?)"} to match a double-quoted
string. Compare with the example in the next page.
\sectiontitle{Expose anchors}
\cregex{\^{}this|\^{}that} $\to$ \cregex{\^{}(?:this|that)}.\\
\cregex{abc\$|123\$} $\to$ \cregex{(?:abc|123)\$} (only affects Perl).\\
\re{} only tried at places where the anchor (i.e. \cregex{\^{}}) matches.
\end{col1}
\begin{col2}
\sectiontitle{Algebraic identities}
\textbf{Note:} In this section all parenthesis are non-capturing. These are
strictly theoretical equivalences.
\equivcomment{r|s}{s|r}{commutativity for alternation\textsuperscript{$\dagger$}}
\equivcomment{r|(s|t)}{(r|s)|t}{associativity for alternation}
\equivcomment{r|r}{r}{absorption of alternation}
\equivcomment{r(st)}{(rs)t}{associativity for concatenarion}
\equivcomment{r(s|t)}{rs|rt}{left distributivity}
\equivcomment{(s|t)r}{sr|tr}{right distributivity}
\equivcomment{r$\epsilon$}{r}{identity for concatenation}
\equivcomment{r*r*}{r*}{closure absorption}
\equivcomment{r*}{$\epsilon$|r|rr|\dots}{Kleene closure}
\equivcomment{rr*}{r*r}{\cregex{r+}}
\equivalence{(r*)*}{r*}
\equivalence{(r*|s*)*}{(r*s*)*}
\equivalence{(r*s*)*}{(r|s)*}
\equivalence{(rs)*r}{r(sr)*}
\equivalence{(r|s)*}{(r*s)*r*}
\begin{cheatnote}
$\dagger$ It is not the same in terms of performance for a NFA engine, where
alternatives are tried in order of appearance.\\
\end{cheatnote}
\sectiontitle{Expose literal text}
\cregex{this|that} $\to$ \cregex{th(?:is|at)}.\\
\cregex{-\{5,7\}} $\to$ \cregex{------\{0,2\}}.\\
The engine can use a fast substring search (like the
\href{https://en.wikipedia.org/wiki/Boyer–Moore_string_search_algorithm}{Boyer-Moore}
or the Hume-Sunday algorithms) to find the literal text (i.e. \cregex{th}) and
then match the rest of the \re.
\end{col2}
\begin{col3}
\sectiontitle{Loop unrolling}
Useful to optimise a regex with the following structure:
\cregex{(normal|special)*}. This can be changed to:\\
\cregex{opening normal*(?:special normal*)* closing},\\
where \regex{opening}, \regex{normal}, \regex{special} and \regex{closing} are
all regular expressions. It can be used to optimise any number of alternatives,
like in \cregex{(\re{}1|\re{}2|\dots)*}.\\
\textbf{Notes:}
\begin{enumerate}
\item \regex{normal} should be the most common case
\item the start of \regex{normal} and \regex{special} must not match at the
same location.
\item \regex{special} must not match the \emph{empty string}.
\item \regex{special} must be atomic.
\end{enumerate}
See the examples.
\end{col3}
\end{cheatsheet}
\newpage
\begin{cheatsheet}{Regular Expressions Examples 1}
\begin{col1}
\sectiontitle{Match quoted string with escaped quotes}
\reshortexample{./quoted_string.tex}\\
\emph{Note:} Possessive quantifiers prevent very long execution times (due to
the nested quantifiers \cregex{+} and \cregex{*}) when there is no matching.\\
Loop-unrolling version:\\
\reshortexample{./quoted_string_lu.tex}\\
\sectiontitle{Conditional expressions}
\begin{itemize}
\item Backreference as condition: Match a word optionally wrapped in \code{<$\cdots$>}:\\
\reshortexample{./cond_backref.tex}
\item Lookaround as condition: Check for number only if prefixed with ``\code{NUM:}'':\\
\reshortexample{./cond_lookaround.tex}
\end{itemize}
\sectiontitle{Branch reset}
Always capture the number under \cregex{\bs{}1} (or \cregex{\$1}):\\
\reshortexample{./branch_reset.tex}
\sectiontitle{Fix floating-point rounding problems}
Use at most $3$ decimal places. Change numbers like $3.27600000002828$ into
$3.276$; or $4.120000000034$ into $4.12$:\\
\reshortexample{./fixfloat.tex}\\
\end{col1}
\begin{col2}
\sectiontitle{Extract file name from path}
Perl:
\relongexample{extract_filename.regex}
\sectiontitle{Adding thousand separators to a number}
Using lookaround:\\
\reshortexample{./thousandsep_1.tex}\\
Without using lookaround (in Perl):
\relongexample{thousandsep_2.regex}
\sectiontitle{Match continuation line}
Match a single ``logical'' line split into multiple lines by adding \cregex{\bs}
at the end of each split. Example:\\
\texttt{%
\mbox{}\ \ SRC=a.c b.c c.c \bs\\
\mbox{}\ \ \ \ \ \ d.c e.c}
\reshortexample{./cont_line.tex}\\
Loop-unrolling version:
\relongexample{cont_line_lu.regex}
\end{col2}
\begin{col3}
\sectiontitle{Match a date (month and day)}
\relongexample{date.regex}
\sectiontitle{Match time (am/pm)}
\reshortexample{./time12.tex}\\
\sectiontitle{Match time (24 hours)}
\reshortexample{./time24_1.tex}\\
or\\
\reshortexample{./time24_2.tex}\\
\end{col3}
\end{cheatsheet}
\newpage
\begin{cheatsheet}{Regular Expressions Examples 2}
\begin{col1}
\sectiontitle{Parse a CSV file}
This regex matches each field in a CSV line, supporting fields with or without
surrounding double-quotes. In the former case, a double quote is represented by
a pair of double quotes:
\relongexample{parse_csv.regex}
The line with the ``slow'' comment can be made faster using loop unrolling,
with \regex{normal} = \cregex{[\^{}"]} and \regex{special} = \cregex{""}:
\reshortexample{./parse_csv_lu.tex}\\
\sectiontitle{Match IP address}
Using Perl regex object for clarity:
\relongexample{ip.regex}
\sectiontitle{Match an email address}
\relongexample{email_addr.regex}
\end{col1}
\begin{col2}
\sectiontitle{Match a URL}
\relongexample{url.regex}
\sectiontitle{Match closing XML tag}
Using lazy quantifier:
\reshortexample{./matchclosetag_lazy.tex}\\
Using greedy quantifier:
\reshortexample{./matchclosetag_greedy.tex}\\
Loop-unrolling with
\regex{normal} = \cregex{[\^{}<]} and
\regex{special} = \cregex{(?!</?B>)<}:\\
\relongexample{matchclosetag_lu.regex}
\end{col2}
\begin{col3}
\sectiontitle{Balanced parentheses (static)}
Match up to $n$ levels of nested parentheses:
\relongexample{balanced_paren_static.regex}
\sectiontitle{Balanced parentheses (dynamic)}
Match a function call with balanced parentheses:
\relongexample{balanced_paren_dynamic.regex}
\end{col3}
\end{cheatsheet}
\newpage
\begin{cheatsheet}{Regular Expressions Usage in Programming Languages and Tools}
\begin{col1}
\sectiontitle{Perl}
\insertcode{Perl}{./src_examples/finddbl.pl}
\end{col1}
\begin{col2}
\sectiontitle{Java}
\insertcode{Java}{./src_examples/example.java}
\mbox{}% Used to leave some vertical space
\sectiontitle{Python}
\insertcode{Python}{./src_examples/example.py}
\end{col2}
\begin{col3}
\sectiontitle{\dnet\ (C\#)}
\insertcode{CSharp}{./src_examples/example.cs}
\mbox{}% Used to leave some vertical space
\sectiontitle{Automated editing}
\insertcode{Bash}{./src_examples/commands.sh}
\end{col3}
\end{cheatsheet}
\end{document}