Skip to content
Snippets Groups Projects
Commit 23483f3f authored by Prof. Dr. Robert Jäschke's avatar Prof. Dr. Robert Jäschke
Browse files

+Tipps

parent 1e5c3d3f
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags:
# 12. Übungsblatt
Mit diesem Python-Code können Sie Ihren regulären Ausdruck testen:
%% Cell type:code id: tags:
```
import re
"""
Ändern Sie den folgenden regulären Ausdruck, so dass alle
positiven Muster erkannt werden, aber kein negatives Muster.
"""
muster = re.compile(" ")
muster = re.compile("Z")
positive = [
"rap them",
"tapeth",
"apth",
"wrap/try",
"sap tray",
"87ap9th",
"apothecary"
]
negative = [
"aleht",
"happy them",
"tarpth",
"Apt",
"peth",
"tarreth",
"ddapdg",
"apples",
"shape the"
]
# testen, ob alle positiven Muster richtig erkannt werden
positive_not_matched = [s for s in positive if not muster.findall(s)]
if positive_not_matched:
print("Folgende positive Muster wurden nicht erkannt:", ", ".join(positive_not_matched))
print("Folgende positiven Muster wurden nicht erkannt:", ", ".join(positive_not_matched))
# testen, ob keine negativen Muster erkannt werden
negative_matched = [s for s in negative if muster.findall(s)]
if negative_matched:
print("Folgende negativen Muster wurden erkannt:", ", ".join(negative_matched))
if not positive_not_matched and not negative_matched:
print("Herzlichen Glückwunsch, Sie haben das richtige Muster gefunden!")
```
%% Cell type:markdown id: tags:
Nachfolgend noch einige Beispiele zur Verwendung von regulären Ausdrücke mit Python:
%% Cell type:code id: tags:
```
# Funktionen für reguläre Ausdrücke werden im Modul "re" bereitgestellt
import re
# die Methode "findall" findet alle Teilzeichenketten in einer Zeichenkette,
# die auf das angegebene Muster passen
re.findall("cat|dog", "This sentence contains a dog.")
```
%% Cell type:code id: tags:
```
# die Methode "match" testet, ob die gesamte Zeichenkette auf das angegebene Muster passt
re.match(".*dog\\.", "This sentence contains a dog.")
```
%% Cell type:code id: tags:
```
re.match(".*(cat|dog)", "This sentence contains a cat.")
```
%% Cell type:markdown id: tags:
Mit "match" können wir beispielsweise unsere Ergebnisse für Aufgabe 1 prüfen:
%% Cell type:code id: tags:
```
if re.match("[hc]?at", "cat"):
print("Wort wurde erkannt")
else:
print("Wort wurde nicht erkannt")
```
%% Cell type:markdown id: tags:
%% Cell type:code id: tags:
```
# Es gibt eine umfangreiche eingebaute Hilfe:
help(re)
```
%% Cell type:code id: tags:
```
```
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment