Fișă de bază pentru regex

O expresie regulată (regex) este un model care potrivește textul. Fiecare simbol, numit token, schimbă comportamentul modelului. Fișa de mai jos enumeră cei mai utili tokeni, cu un sens simplu și un mic exemplu de copiat și testat.

Actualizat:

TokenÎnțelesExemplu
.Matches any single character except newline.a.c matches abc, a c
*Matches the preceding token zero or more times.ab* matches a, abb
+Matches the preceding token one or more times.ab+ matches ab, abb
?Makes the preceding token optional (zero or one).colou?r matches color, colour
[]Character set: matches any one character inside.[aeiou] matches any vowel
[^]Negated set: matches any character NOT inside.[^0-9] matches any non-digit
\dMatches any digit (0-9).\d+ matches 42, 007
\wMatches any word character (a-z, A-Z, 0-9, _).\w+ matches hello_1
\sMatches any whitespace (space, tab, newline).a\sb matches a b
^Anchors the match to the start of a line/string.^Hello matches start of string
$Anchors the match to the end of a line/string.world$ matches end of string
|Alternation: matches the pattern on either side.cat|dog matches cat or dog
()Groups a sub-pattern (and captures it).(ab)+ matches ab, abab
{n,m}Quantifier: match the preceding token n to m times.a{2,4} matches aa, aaaa
(?i)Inline flag: makes the pattern case-insensitive.(?i)hello matches HELLO

Note

Întrebări frecvente

Cu ce se potrivește punctul (.) ?
În mod implicit punctul se potrivește cu orice caracter, în afară de o linie nouă. Pentru un punct literal trebuie escapat ca \.
Care este diferența între * și + ?
Asteriscul * se potrivește cu tokenul anterior de zero sau mai multe ori, deci 'ab*' se potrivește și cu 'a'. Plusul + cere cel puțin unul, se potrivește cu 'ab' dar nu doar cu 'a'.
Cum potrivesc o cifră sau un caracter de cuvânt?
Folosește \d pentru orice cifră (0-9) și \w pentru orice caracter de cuvânt (litere, cifre, subliniere). Negările sunt \D și \W.
La ce servesc ^ și $ ?
^ ancorează potrivirea la începutul șirului sau liniei; $ la sfârșit. Împreună, ^model$ forțează potrivirea întregului șir.