This is an old revision of the document!


Regex tutorial  —  Cheatsheet by examples

Izvor: Jonny Fox, Medium

Regularni izrazi (regex ili regexp) su izuzetno korisni u izvlačenju informacija iz bilo kog teksta traženjem jednog ili više podudaranja određenog obrasca pretrage (tj. određenog niza ASCII ili unikod znakova).

Polja primene se kreću od provere valjanosti do raščlanjivanja/zamene stringova, prolaska kroz prevođenje podataka u druge formate i veb skrapinga.

Jedna od najzanimljivijih karakteristika je da kada se nauči sintaksa, ovaj alat može da se koristi u (skoro) svim programskim jezicima (JavaScript, Java, VB, C #, C / C++, Pithon, Perl, Rubi , Delphi, R, Tcl, d mnogi drugi) sa najmanjim razlikama u pogledu podrške najnaprednijih funkcija i verzija sintakse koje podržavaju mašine.

Evo nekih primerima i objašnjenja.

^The odgovara bilo kom nizu koji počinje sa The
end$ odgovara nizu koji se završava sa end
^The end$ tačno podudaranje niza (počinje i završava se sa The end)
roar odgovara bilo kom stringu koji ima tekst roar u sebi

abc* odgovara nizu koji ima ab praćeno sa nula ili više c
abc+ odgovara nizu koji ima ab praćeno sa jedanim ili više c
abc? odgovara nizu koji ima ab praćeno sa nula ili jedanim c
abc{2} odgovara nizu koji ima ab praćeno sa 2 c
abc{2,} odgovara nizu koji ima ab praćeno sa 2 ili više c
abc{2,5} odgovara nizu koji ima ab praćeno sa 2 do 5 c
a(bc)* odgovara nizu koji ima a praćeno sa nula ili više kopija niza bc
a(bc){2,5} odgovara nizu koji ima a praćeno sa 2 do 5 kopija niza bc

a(b|c) odgovara nizu koji ima a praćeno sa b ili c a[bc] isto kao i prethodni

\d odgovara jedan karakter koji je cifra
\w odgovara znaku reči (alfanumerički znak plus donja crta)
\s odgovara razmaku (uključuje tabulatore i prelome redova)
. odgovara bilo koji karakter

Pažljivo koristite operator . jer su često klasa ili negirana klasa znakova (o čemu ćemo dalje govoriti) brži i precizniji.

\d, \w i \s takođe predstavljaju svoje negacije sa \D, \W i \S respektivno .

Na primer, \D će izvršiti obrnuto podudaranje u odnosu na ono dobijeno sa \d.
\D odgovara jedan necifren znak.

Da biste bili shvaćeni bukvalno, morate izbeći znakove ^.[$()|*+?{ obrnutom kosom crtom jer oni imaju posebno značenje.
$d odgovara nizu koji ima $ ispred jedne cifre.

Imajte na umu da možete da uparite i znakove koji se ne mogu štampati kao što su tabulatori \t, novi redovi \n, znakovi koji se vraćaju \r.

\s odgovara bilo kom znaku razmaka. To je ekvivalentno izlaznim sekvencama i Unicode kategorijama navedenim u sledećoj tabeli.

KategorijaOpis
\fZnak za novi obrazac (FF), \u000C.
\nZnak za novu liniju (LF), \u000A.
\rPovratni karakter (CR), \u000D.
\tTab znak, \u0009.
\vVertikalni tab znak, \u000B.
\x85The NEXT LINE (NEL) character, \u0085.
\p{Z}Odgovara svim znakovima za razdvajanje. Ovo uključuje kategorije Zs, Zl i Zp.

We are learning how to construct a regex but forgetting a fundamental concept: flags.

A regex usually comes within this form /abc/, where the search pattern is delimited by two slash characters (/).
At the end we can specify a flag with these values (we can also combine them each other):

\g (global) does not return after the first match, restarting the subsequent searches from the end of the previous match
\m (multi-line) when enabled ^ and $ will match the start and end of a line, instead of the whole string
\i (insensitive) makes the whole expression case-insensitive (for instance /aBc/i would match AbC)

Intermediate topics

a(bc) parentheses create a capturing group with value bc
a(?:bc)* using ?: we disable the capturing group bc
a(?<foo>bc) using ?<foo> we put a name to the group bc

This operator is very useful when we need to extract information from strings or data using your preferred programming language. Any multiple occurrences captured by several groups will be exposed in the form of a classical array: we will access their values specifying using an index on the result of the match.

If we choose to put a name to the groups (using (?<foo>…)) we will be able to retrieve the group values using the match result like a dictionary where the keys will be the name of each group.

[abc] matches a string that has either an a or a b or a c is the same as a|b|c
[a-c] same as previous
[a-fA-F0-9] a string that represents a single hexadecimal digit, case insensitively
[0-9]% a string that has a character from 0 to 9 before a % sign
[^a-zA-Z] a string that has not a letter from a to z or from A to Z. In this case the ^ is used as negation of the expression

Remember that inside bracket expressions all special characters (including the backslash ) lose their special powers: thus we will not apply the “escape rule”.

The quantifiers ( * + {}) are *greedy operators*, so they expand the match as far as they can through the provided text.

For example, <.+> matches <div>simple div</div> in This is a <div>simple div</div> test. In order to catch only the div tag we can use a ? to make it lazy
<.+?> matches any character one or more times included inside < and >, expanding as needed.

Notice that a better solution should avoid the usage of . in favor of a more strict regex: <[^<>]+> matches any character except < or > one or more times included inside < and >.


Advanced topics

\babc\b performs a “whole words only” search

\b represents an anchor like caret (it is similar to $ and ^) matching positions where one side is a word character (like \w) and the other side is not a word character (for instance it may be the beginning of the string or a space character).

It comes with its negation, \B. This matches all positions where \b doesn’t match and could be if we want to find a search pattern fully surrounded by word characters. \Babc\B matches only if the pattern is fully surrounded by word characters.

([abc])\1 using \1 it matches the same text that was matched by the first capturing group.
([abc])([de])\2\1 we can use \2 (3, 4, etc.) to identify the same text that was matched by the second (third, fourth, etc.) capturing group.
(?<foo>[abc])\k<foo> we put the name foo to the group and we reference it later (k<foo>). The result is the same of the first regex.

d(?=r) matches a d only if it is followed by r, but r will not be part of the overall regex match.
(?⇐r)d matches a d only if it is preceded by an r, but r will not be part of the overall regex match.

You can use also the negation operator!

d(?!r) matches a d only if is not followed by r, but r will not be part of the overall regex match.
(?<!r)d matches a d only if is not preceded by an r, but r will not be part of the overall regex match.

  • kb/zapisi/regex_main.1692108922.txt.gz
  • Last modified: 2023/08/15 14:15
  • by milano