Spiekbriefje regex-basis

Een reguliere expressie (regex) is een patroon dat tekst matcht. Elk symbool, een token genoemd, verandert het gedrag van het patroon. Het blad hieronder geeft de meest gebruikte tokens met een heldere betekenis en een klein voorbeeld om te kopiëren en te testen.

Bijgewerkt:

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

Opmerkingen

Veelgestelde vragen

Waar komt het punt (.) mee overeen?
Standaard komt de punt overeen met elk enkel teken behalve een newline. Voor een letterlijke punt moet je hem escapen als \.
Wat is het verschil tussen * en + ?
Het sterretje * komt nul of meer keer overeen met het voorgaande token, dus 'ab*' komt ook met 'a' overeen. De plus + vereist minstens één keer, dus 'ab' maar niet alleen 'a'.
Hoe kom ik overeen met een cijfer of woordteken?
Gebruik \d voor een cijfer (0-9) en \w voor een woordteken (letters, cijfers, underscore). De negationen zijn \D en \W.
Waar dienen ^ en $ voor?
^ verankert de match aan het begin van de string of regel; $ aan het eind. Samen dwingt ^patroon$ de hele string te matchen.