Englisch | Русский | Deutsch | Български | Français | Español |
Reguläre Ausdrücke (RegEx)¶
Einführung¶
Reguläre Ausdrücke sind eine praktische Möglichkeit, Textmuster anzugeben.
Mit regulären Ausdrücken können Sie Benutzereingaben validieren, nach Mustern wie E-Mail-Adressen oder Telefonnummern auf Webseiten oder in Dokumenten suchen und so weiter.
Below is the complete regular expressions cheat sheet.
Zeichen¶
Einfache Übereinstimmungen¶
Any single character (except special regex characters) matches itself. A series of (not special) characters matches that series of characters in the input string.
RegEx | passt auf |
---|---|
foobar |
foobar |
Nicht druckbare Zeichen (Escape-Codes)¶
To specify character by its Unicode code, use the prefix \x
followed by the hex code.
For 3-4 digits code (after U+00FF), enclose the code into braces.
RegEx | passt auf |
---|---|
\xAB |
character with 2-digit hex code AB |
\x{AB20} |
character with 1..4-digit hex code AB20 |
foo\x20bar |
foo bar (Beachten Sie das Leerzeichen in der Mitte) |
There are a number of predefined escape-codes for non-printable characters, like in C language:
RegEx | passt auf |
---|---|
\t |
(Horizontal-)Tabulator (HT / TAB), identisch mit \x09 |
\n |
line feed (LF), same as \x0a |
\r |
carriage return (CR), same as \x0d |
\f |
Formularvorschub (FF), wie \x0c |
\a |
Alarm (BEL), gleichbedeutend mit \x07 |
\e |
Escape (ESC), genauso wie \x1b |
\cA … \cZ |
chr(0) to chr(25).
For example,
\cI matches the tab-char.Lower-case letters „a“…“z“ are also supported.
|
Maskierung (Escaping)¶
To represent special regex character (one of .+*?|\()[]{}^$
), prefix it with a backslash \
.
The literal backslash must be escaped too.
RegEx | passt auf |
---|---|
\^FooBarPtr |
^FooBarPtr , this is ^ and not start of line |
\[a\] |
[a] , this is not character class |
Zeichenklassen¶
Benutzerdefinierte Zeichenklassen¶
Character class is a list of characters inside square brackets []
.
The class matches any single character listed in this class.
RegEx | passt auf |
---|---|
foob[aeiou]r |
foobar , foober usw., nicht aber foobbr , foobcr etc. |
You can „invert“ the class - if the first character after the [
is
^
, then the class matches any character except the characters listed
in the class.
RegEx | passt auf |
---|---|
foob[^aeiou]r |
foobbr , foobcr usw., aber nicht foobar , foober etc. |
Within a list, the dash -
character is used to specify a range, so that
a-z
represents all characters between a
and z
, inclusive.
If you want the dash -
itself to be a member of a class, put it at the start
or end of the list, or escape it with a backslash.
If you want ]
as part of the class you may place it at the start of list or
escape it with a backslash.
RegEx | passt auf |
---|---|
[-az] |
a , z und - |
[az-] |
a , z und - |
[a\-z] |
a , z und - |
[az] |
Zeichen von a bis z |
[\n-\x0D] |
characters from chr(10) to chr(13) |
Meta-Classes¶
There are a number of predefined character classes that keeps regular expressions more compact, „meta-classes“:
RegEx | passt auf |
---|---|
\w |
an alphanumeric character, including _ |
\W |
a non-alphanumeric |
\d |
a numeric character (same as [0-9] ) |
\D |
ein nichtnumerisches Zeichen |
s |
ein beliebiger Leerraum (dasselbe wie [ \t\n\r\f] ) |
\S |
a non-space |
\h |
horizontal whitespace: the tab and all characters
in the „space separator“ Unicode category
|
\H |
jedes Zeichen, das kein horizontaler Leerraum ist |
\v |
vertical whitespace: all characters treated as
line-breaks in the Unicode standard
|
\V |
jedes Zeichen, das nicht einen vertikalen Abstand liefert |
You may use all meta-classes, mentioned in the table above, within user character classes.
RegEx | passt auf |
---|---|
foob\dr |
foob1r , foob6r and so on, but not foobar , foobbr and so on |
foob[\w\s]r |
foobar , foob r , foobbr and so on, but not foob1r , foob=r and so on |
Bemerkung
Die Zeichenklassen \w
, \W
, \s
und \S
sind in den Properties SpaceChars und WordChars definiert.
So you can redefine these classes.
Grenzen¶
Zeilengrenzen¶
Meta-char | passt auf |
---|---|
. |
any character, can include line-breaks |
^ |
zero-length match at start of line |
$ |
zero-length match at end of line |
\A |
zero-length match at the very beginning |
\z |
zero-length match at the very end |
\Z |
like \z but also matches before the final line-break |
Examples:
RegEx | passt auf |
---|---|
^foobar |
foobar nur, wenn es am Anfang der Zeile steht |
foobar$ |
foobar nur wenn es am Zeilenende steht |
^foobar$ |
foobar nur wenn davor und danach kein sonstiges Zeichen innerhalb der Zeile steht |
foob.r |
foobar , foobbr , foob1r usw. |
Meta-char ^
matches zero-length position at the beginning of the input string.
$
- at the ending.
If modifier /m is on, they also match at the beginning/ending
of individual lines in the multi-line text.
Beachten Sie, dass sich in der Sequenz \x0D\x0A
keine leere Zeile befindet.
Bemerkung
Wenn Sie die Unicode-Version verwenden, dann stimmen ^
/$
auch mit \x2028
, \x2029
, \x0B
, \x0C
or \x85
überein.
Meta-char \A
matches zero-length position at the very beginning of the input string,
\z
- at the very ending. They ignore modifier /m.
\Z
is like \z
but also matches before the final line-break (LF and CR LF).
Behaviour of \A
, \z
, \Z
is made like in most of major regex engines (Perl, PCRE, etc).
Meta-char .
(dot) by default matches any character, but if you
turn off the modifier /s, then it won’t match line-breaks inside the string.
Note that ^.*$
does not match a string between \x0D\x0A
,
because this is unbreakable line separator.
But it matches the empty string within the sequence \x0A\x0D
because
this is 2 line-breaks in the wrong order.
Bemerkung
Multi-line processing can be tuned by properties LineSeparators and UseLinePairedBreak.
Sie können also Zeilenschaltungen im Unix-Stil \n
oder im DOS/Windows-Stil \r\n
verwenden oder beides (Standardverhalten wie oben beschrieben).
Wenn Sie eine mathematisch korrekte Beschreibung bevorzugen, können Sie sie unter www.unicode.org finden <http://www.unicode.org/unicode/reports/tr18/>__.
Wortgrenzen (Ankerpunkte)¶
RegEx | passt auf |
---|---|
\b |
eine Wortgrenze |
\B |
keine Wortgrenze (Ankerpunkt, der entweder beidseits von w oder W umgeben ist) |
Eine Wortgrenze \b
ist eine Stelle zwischen zwei Zeichen, von denen eines \w
und das andere ein \W
ist (Reihenfolge egal).
Quantifizierung¶
Quantifiers¶
Auf jedes Element eines regulären Ausdrucks kann ein Quantifizierer folgen. Dieser gibt die Anzahl der Wiederholungen des Elements an.
RegEx | passt auf |
---|---|
{n} |
genau n mal |
{n,} |
mindestens n mal |
{n,m} |
zumindest "n" aber nicht mehr als "m" mal |
* |
nicht bis beliebig oft vorkommend, alternative Notation: {0,} |
+ |
mindestens einmal vorkommend, alternative Notation: {1,} |
? |
höchstens einmal vorkommend, alternative Notation: {0,1} |
Innerhalb der geschweiften Klammern {n, m}
geben Sie also die Mindest-( n
) und Höchstanzahl ( m
) für das Vorkommen des voranstehenden Elements an.
The {n}
is equivalent to {n,n}
and matches exactly n
times.
The {n,}
matches n
or more times.
There is no practical limit to the values n and m (limit is maximal signed 32-bit value).
RegEx | passt auf |
---|---|
foob.*r |
foobar , foobalkjdflkj9r und foobr |
foob.+r |
foobar , foobalkjdflkj9r` aber nicht foobr |
foob.?r |
foobar , foobbr und foobr , aber nicht foobalkj9r |
fooba{2}r |
foobaar |
fooba{2,}r |
foobaar , foobaaar , foobaaaar usw. |
fooba{2,3}r |
foobaar oder foobaaar , aber nicht foobaaaar |
(foobar){8,10} |
8…10 instances of foobar (() is group) |
Gier (greediness)¶
Quantifiers in „greedy“ mode takes as many as possible, in „lazy“ mode - as few as possible.
By default all quantifiers are „greedy“.
Append the character ?
to make any quantifier „lazy“.
Für den String abbbbc
:
RegEx | passt auf |
---|---|
b+ |
bbbb |
b+? |
b |
b*? |
leerer String |
b{2,3}? |
bb |
b{2,3} |
bbb |
You can switch all quantifiers into „lazy“ mode (modifier /g, below we use in-line modifier change).
RegEx | passt auf |
---|---|
(?-g)b+ |
b |
Possessive Quantifier¶
The syntax is: a++
, a*+
, a?+
, a{2,4}+
.
Currently it’s supported only for simple braces, but
not for braces after group like (foo|bar){3,5}+
.
This regex feature is described here. In short, possessive quantifier speeds up matching in complex cases.
Choice¶
Expressions in the choice are separated by vertical bar |
.
fee|fie|foe
passt also zu einem fee
, fie
oder foe
in der Zielzeichenfolge (ebenso wie fee|fie|foe
).
Zum ersten Ausdruck zählt alles vom letzten Musterbegrenzer ((
, [
oder dem Anfang des Musters) bis vor das erste | ``, und der letzte Ausdruck umfasst alles nach dem letzten ``|
zum nächsten Musterbegrenzer.
Klingt etwas kompliziert, daher setzt man üblicherweise die Alternativausdrücke in Klammern, um damit ihren Anfang und das Ende deutlicher erkennbar zu machen.
Die alternativen Ausdrücke werden von links nach rechts durchgetestet, und der erste passende wird verwendet.
Beispielsweise wird der reguläre Ausdruck foo|foot
in der Zeichenfolge barefoot
nur foo
ergeben. Dies war nämlich die erste passende Alternative.
Denken Sie auch daran, dass |
innerhalb eckiger Klammern als Literal interpretiert wird. Wenn Sie also [fee|fie|foe]
schreiben, bedeutet das wirklich nur die Zeichenklasse [efio |]
.
RegEx | passt auf |
---|---|
foo(bar|foo) |
foobar oder foofoo |
Groups¶
The brackets ()
are used to define groups (ie subexpressions).
Bemerkung
Group positions, lengths and actual values will be in MatchPos, MatchLen and Match.
Sie können sie durch Substitute ersetzen.
Groups are numbered from left to right by their opening parenthesis (including nested groups). First group has index 1. The entire regex has index 0.
For string
foobar
, the regex(foo(bar))
will find:
Group Value 0 foobar
1 foobar
2 bar
Rückreferenzen¶
Meta-chars \1
through \9
are interpreted as backreferences to groups.
They match the previously found group with the specified index.
RegEx | passt auf |
---|---|
(.)\1+ |
aaaa und cc |
(.+)\1+ |
auch abab und 123123 |
RegEx (['"]?)(\d+)\1
matches "13"
(in double quotes), or '4'
(in
single quotes) or 77
(without quotes) etc.
Named Groups and Backreferences¶
To make some group named, use this syntax: (?P<name>expr)
. Also Perl syntax is supported: (?'name'expr)
.
Name of group must be valid identifier: first char is letter or „_“, other chars are alphanumeric or „_“. All named groups are also usual groups and share the same numbers 1 to 9.
Backreferences to named groups are (?P=name)
, the numbers \1
to \9
can also be used.
RegEx | passt auf |
---|---|
(?P<qq>['"])\w+(?P=qq) |
"word" and 'word' |
Modifikatoren¶
Modifikatoren gestatten eine Verhaltensänderung regulärer Ausdrücke.
You can set modifiers globally in your system or change inside the regular expression using the (?imsxr-imsxr).
Bemerkung
Um den Wert eines Modifikators festzulegen, verwenden Sie entweder ModifierStr oder die entsprechende TRegExpr
-Eigenschaft namens `Modifier* <tregexpr.html#modifieri> __.
Die Standardwerte sind in den globalen Variablen definiert. Beispielsweise legt die globale Variable `` RegExprModifierX`` den Standardwert für die ModifierX
-Eigenschaft fest.
i: Groß- und Kleinschreibung ignorieren¶
Groß- und Kleinschreibung wird nicht berücksichtigt. Verwendet ansonsten die in Ihrem System eingestellten Spracheinstellungen, siehe auch InvertCase.
m: mehrzeilige Zeichenketten¶
String zeilenweise als mehrzeiligen Text behandeln. ^
und $
finden damit Anfang und Ende in jeder beliebigen Zeile innerhalb des Strings.
Siehe auch Zeilengrenzen.
s: einzeilige Zeichenfolgen¶
Gesamte Zeichenfolge als einzelne Zeile behandeln. .
passt dann auf jedes beliebige Zeichen, insbesondere auch auf Zeilenwechsel.
Siehe auch Zeilengrenzen, die normalerweise nicht gefunden würden.
g: Gierigkeit¶
Bemerkung
In TRegExpr nur als Modifikator verfügbar.
Wenn Sie auf Off
umschalten, bringen Sie alle Quantifier vom gierigen (greedy) in den ``trägen (non-greedy)<#greedy>`__-Modus.
Wenn also der Modifikator /g
Off
ist, funktioniert +
als +?
, *
als *?
und so weiter.
Standardmäßig ist dieser Modifikator On
.
x: erweiterte Syntax¶
Ermöglicht den regulären Ausdruck zu kommentieren und in mehrere Zeilen aufzuteilen.
Wenn dieser Modifikator On
ist, ignorieren wir alle Leerräume, sofern sie weder maskiert noch innerhalb einer Zeichenklasse stehen.
Und das Zeichen `` #`` trennt Kommentare ab.
Eine mehrzeilige Darstellung macht übrigens reguläre Ausdrücke oft besser lesbar:
(
(abc) # Kommentar 1
#
(efg) # Kommentar 2
)
Dies bedeutet auch: wenn Sie literale Whitespace- oder #
Zeichen in dem Muster (außerhalb einer Zeichenklasse, wo sie nicht von /x
betroffen sind) angeben möchten, müssen Sie diese entweder maskieren oder als Oktal- oder Hex-Codes schreiben.
r: russische Zeichenbereiche¶
Bemerkung
In TRegExpr nur als Modifikator verfügbar.
In der russischen ASCII-Tabelle sind die Zeichen ё
/ Ё
separat untergebracht.
Die übrigen großen und kleinen russische Schriftzeichen liegen jeweils in getrennten Bereichen, analog wie bei den englischen. Ich wollte eine praktische Kurzform.
Mit diesem Modifikator können Sie also statt [а-яА-ЯёЁ]
einfach [а-Я]
schreiben, wenn Sie sämtliche russischen Zeichen benötigen.
Wenn dieser Modifikator On
ist:
RegEx | passt auf |
---|---|
а-я |
Kleinbuchstaben, von а bis я sowie ё |
А-Я |
Großbuchstaben, von A bis Я sowie Ё |
а-Я |
Sämtliche russischen Schriftzeichen |
Dieser Modifikator ist standardmäßig Ein
.
Assertions¶
Positive lookahead assertion: foo(?=bar)
matches „foo“ only before „bar“, and „bar“ is excluded from the match.
Negative lookahead assertion: foo(?!bar)
matches „foo“ only if it’s not followed by „bar“.
Positive lookbehind assertion: (?<=foo)bar
matches „bar“ only after „foo“, and „foo“ is excluded from the match.
Negative lookbehind assertion: (?<!foo)bar
matches „bar“ only if it’s not prefixed with „foo“.
Limitations:
- Brackets for lookahead must be at the very ending of expression, and brackets for lookbehind must be at the very beginning. So assertions between choices
|
, or inside groups, are not supported. - For lookbehind
(?<!foo)bar
, regex „foo“ must be of fixed length, ie contains only operations of fixed length matches. Quantifiers are not allowed, except braces with the repeated numbers{n}
or{n,n}
. Char-classes are allowed here, dot is allowed,\b
and\B
are allowed. Groups and choices are not allowed. - For other 3 assertion kinds, expression in brackets can be of any complexity.
Non-capturing Groups¶
Syntax is like this: (?:expr)
.
Such groups do not have the „index“ and are invisible for backreferences. Non-capturing groups are used when you want to group a subexpression, but you do not want to save it as a matched/captured portion of the string. So this is just a way to organize your regex into subexpressions without overhead of capturing result:
RegEx | passt auf |
---|---|
(https?|ftp)://([^/\r\n]+) |
https und sorokin.engineer in https://sorokin.engineer |
(?:https?|ftp)://([^/\r\n]+) |
nur sorokin.engineer in https://sorokin.engineer |
Atomic Groups¶
Syntax is like this: (?>expr|expr|...)
.
Atomic groups are special case of non-capturing groups. Description of them.
Inline Modifiers¶
Syntax for one modifier: (?i)
to turn on, and (?-i)
to turn off. Many modifiers are allowed like this: (?msgxr-imsgxr)
.
You may use it inside regular expression for modifying modifiers on-the-fly.
This can be especially handy because it has local scope in a regular
expression. It affects only that part of regular expression that follows
(?imsgxr-imsgxr)
operator.
And if it’s inside group, it will affect only this group - specifically the part of the group
that follows the modifiers. So in ((?i)Saint)-Petersburg
it affects
only group ((?i)Saint)
so it will match saint-Petersburg
but not saint-petersburg
.
RegEx | passt auf |
---|---|
(?i)Sankt-Petersburg |
`` Sankt-petersburg`` und `` Sankt-Petersburg`` |
(?i)Sankt-(?-i)Petersburg |
Sankt Petersburg aber nicht Sankt petersburg |
(?i)(Sankt-)?Petersburg |
Sankt-petersburg und sankt-petersburg |
((?i)Sankt-)?Petersburg |
saint-Petersburg , aber nicht saint-petersburg |
Comments¶
Syntax is like this: (?#text)
. Text inside brackets is ignored.
Beachten Sie, dass der Kommentar durch die nächstfolgende )
geschlossen wird. Es gibt also keine Möglichkeit, eine schließende runde Klammer )
in den Kommentar einzufügen.
Recursion¶
Syntax is (?R)
, the alias is (?0)
.
The regex a(?R)?z
matches one or more letters „a“ followed by exactly the same number of letters „z“.
The main purpose of recursion is to match balanced constructs or nested constructs. The generic regex is b(?:m|(?R))*e
where „b“ is what begins the construct, „m“ is what can occur in the middle of the construct, and „e“ is what occurs at the end of the construct.
If what may appear in the middle of the balanced construct may also appear on its own without the beginning and ending parts then the generic regex is b(?R)*e|m
.
Subroutine calls¶
Syntax for call to numbered groups: (?1)
… (?90)
(maximal index is limited by code).
Syntax for call to named groups: (?P>name)
. Also Perl syntax is supported: (?&name)
.
This is like recursion but calls only code of capturing group with specified index.
Unicode Categories¶
Unicode standard has names for character categories. These are 2-letter strings. For example „Lu“ is uppercase letters, „Ll“ is lowercase letters. And 1-letter bigger category „L“ is all letters.
- Cc - Control
- Cf - Format
- Co - Private Use
- Cs - Surrrogate
- Ll - Lowercase Letter
- Lm - Modifier Letter
- Lo - Other Letter
- Lt - Titlecase Letter
- Lu - Uppercase Letter
- Mc - Spacing Mark
- Me - Enclosing Mark
- Mn - Nonspacing Mark
- Nd - Decimal Number
- Nl - Letter Number
- No - Other Number
- Pc - Connector Punctuation
- Pd - Dash Punctuation
- Pe - Close Punctuation
- Pf - Final Punctuation
- Pi - Initial Punctuation
- Po - Other Punctuation
- Ps - Open Punctuation
- Sc - Currency Symbol
- Sk - Modifier Symbol
- Sm - Math Symbol
- So - Other Symbol
- Zl - Line Separator
- Zp - Paragraph Separator
- Zs - Space Separator
Meta-character \p
denotes one Unicode char of specified category. Syntax: \pL
and \p{L}
for 1-letter name, \p{Lu}
for 2-letter names.
Meta-character \P
is inverted, it denotes one Unicode char not in the specified category.
These meta-characters are supported within character classes too.
Nachwort¶
In diesem alten Blogeintrag aus dem vorigen Jahrhundert erläutere ich einige Anwendungsfälle von regulären Ausdrücken.