71 lines
2.0 KiB
Python
71 lines
2.0 KiB
Python
|
import re
|
||
|
import unittest
|
||
|
|
||
|
def Telefonnummer(nummer):
|
||
|
#nur noch Zahlen
|
||
|
nummer = re.sub(r"[^\d]", "", nummer)
|
||
|
|
||
|
#1 am Start
|
||
|
if not nummer.startswith("1"):
|
||
|
nummer = "1" + nummer
|
||
|
|
||
|
#Bindestriche
|
||
|
nummer = re.sub(r"(\d{1})(\d{3})(\d{3})(\d{4})", r"1-\2-\3-\4", nummer)
|
||
|
|
||
|
return nummer
|
||
|
|
||
|
|
||
|
#a)
|
||
|
def Gültigkeit(nummer):
|
||
|
match = re.search(r"(1)-([0-9]+)-([0-9]+)-([0-9]+)", Telefonnummer(nummer))
|
||
|
if match:
|
||
|
ortsvorwahl = match.group(2)
|
||
|
amtskennziffer = match.group(3)
|
||
|
vorwahl = match.group(4)
|
||
|
if ortsvorwahl[0] == "0" or ortsvorwahl[0] == "1":
|
||
|
raise ValueError("Ungültige Telefonnummer (erste Ortsvorwahlziffer darf nicht 0 oder 1 sein)")
|
||
|
elif vorwahl[0] == "0" or vorwahl[0] == "1":
|
||
|
raise ValueError("Ungültige Telefonnummer (erste Vorwahlziffer darf nicht 0 oder 1 sein)")
|
||
|
elif vorwahl[1] == "9":
|
||
|
raise ValueError("Ungültige Telefonnummer (zweite Vorwahlziffer darf nicht 9 sein)")
|
||
|
elif len(ortsvorwahl) != 3 or len(amtskennziffer) != 3 or len(vorwahl) != 4:
|
||
|
raise ValueError("Ungültige Telefonnummer (zu lang)")
|
||
|
return Telefonnummer(nummer)
|
||
|
else:
|
||
|
raise ValueError("Ungültige Telefonnummer (falsches Format)")
|
||
|
|
||
|
|
||
|
#b)
|
||
|
|
||
|
class Testnummern(unittest.TestCase):
|
||
|
def setUp(self):
|
||
|
self.test_nummern = ["+1 223-456-7890",
|
||
|
"1-223-456-7890",
|
||
|
"+1 223 456-7890",
|
||
|
"(223) 456-7890",
|
||
|
"1 223 456 7890",
|
||
|
"223.456.7890",
|
||
|
"1-989-111-2222"]
|
||
|
|
||
|
def testnummern(self):
|
||
|
expected_outputs = ["1-223-456-7890",
|
||
|
"1-223-456-7890",
|
||
|
"1-223-456-7890",
|
||
|
"1-223-456-7890",
|
||
|
"1-223-456-7890",
|
||
|
"1-223-456-7890",
|
||
|
"1-989-111-2222"]
|
||
|
|
||
|
for i, number in enumerate(self.test_nummern):
|
||
|
try:
|
||
|
result = Gültigkeit(number)
|
||
|
self.assertEqual(result, expected_outputs[i])
|
||
|
except ValueError as e:
|
||
|
self.assertRaises(ValueError)
|
||
|
|
||
|
|
||
|
if __name__ == '__main__':
|
||
|
unittest.main()
|
||
|
|
||
|
|