Huskeseddel til regex-grundlæggende

Et regulært udtryk (regex) er et mønster, der matcher tekst. Hvert symbol, kaldet en token, ændrer mønstrets adfærd. Arkivet nedenfor viser de mest brugte tokens med et klart sprog og et lille eksempel til kopiering og test.

Opdateret:

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

Noter

Ofte stillede spørgsmål

Hvad matcher punktum (.) ?
Som standard matcher punktum ethvert tegn undtagen en ny linje. For at matche et bogstaveligt punktum skal du escape det som \.
Hvad er forskellen på * og + ?
Stjernen * matcher det forrige token nul eller flere gange, så 'ab*' matcher også 'a'. Plusset + kræver mindst én gang, matcher 'ab' men ikke kun 'a'.
Hvordan matcher jeg et ciffer eller ordtegn?
Brug \d for ethvert ciffer (0-9) og \w for ethvert ordtegn (bogstaver, cifre, understregning). Negeringerne er \D og \W.
Hvad bruges ^ og $ til?
^ forankrer matchen til starten af strengen eller linjen; $ til slutningen. Sammen tvinger ^mønster$ hele strengen til at matche.