Přeskočit na obsah

Re/Cvičení

Z Wikiverzity
< Re
Jak používat klasifikační nálepkuTato stránka je součástí projektu:
Příslušnost: všeobecná
Tato stránka není ještě hotová.

Cvičení 1: vypiš všechna čísla

[editovat]
import re

text = "Je rok 2025 a já mám 2 děti a 1 ženu."
digits = re.findall("", text)
print(digits)  # Expected output: ['2', '0', '2', '5', '2', '1']

Cvičení 2: vypiš pouze rok

[editovat]
import re

text = "Je rok 2025 a já mám 2 děti a 1 ženu."
digits = re.findall("", text)
print(digits)

Cvičení 3: vyextrahuj e-mailové adresy

[editovat]
import re

text = "Contact us at support@example.com or sales@example.org."
emails = re.findall("", text)
print(emails)  # Expected output: ['support@example.com', 'sales@example.org']

Cvičení 4: vyextrahuj první e-mailovou adresu

[editovat]
import re

text = "Contact us at support@example.com or sales@example.org."
emails = re.findall("", text)
print(emails)  # Expected output: ['support@example.com']

Cvičení 5: Vyextrahuj slova začínající na A/a

[editovat]
import re

text = "Apples are amazing, but avocados are awesome too."
# Write your regex to find words starting with 'a'
words = re.findall(r"", text)
print(words)  # Expected output: ['Apples', 'are', 'amazing', 'avocados', 'are', 'awesome']

Cvičení 6: definuj čísla ve správném formátu

[editovat]
import re

phone_numbers = [
    "123-456-7890",
    "987-654-3210",
    "12345-6789",
    "123-45-67890"
]

for number in phone_numbers:
    # Write your regex to validate phone numbers
    match = re.match(r"", number)
    print(f"{number}: {'Valid' if match else 'Invalid'}")
# Expected output:
# 123-456-7890: Valid
# 987-654-3210: Valid
# 12345-6789: Invalid
# 123-45-67890: Invalid

Cvičení 6: Nahraď souhlásky hvězdičkou

[editovat]
import re

text = "Regular expressions are powerful."
# Write your regex to replace vowels
result = re.sub(r"", "*", text)
print(result)  # Expected output: "R*g*l*r *xpr*ss**ns *r* p*w*rf*l."

Cvičení 7: Vyextrahuj datumy

[editovat]
import re

text = "Important dates are 12/01/2023 and 25/12/2025."
# Write your regex to find dates
dates = re.findall(r"", text)
print(dates)  # Expected output: ['12/01/2023', '25/12/2025']

Cvičení 8: Docilte výsledku uvedeného níže

[editovat]
import re

usernames = [
    "valid_user",
    "user123",
    "_invalid",
    "a",
    "toolongusername123"
]

for username in usernames:
    # Write your regex to validate usernames
    match = re.match(r"", username)
    print(f"{username}: {'Valid' if match else 'Invalid'}")
# Expected output:
# valid_user: Valid
# user123: Valid
# _invalid: Invalid
# a: Invalid
# toolongusername123: Invalid