#๐Ÿ”’ My REGEX almost passes tests. What to change?

4 messages ยท Page 1 of 1 (latest)

remote jolt
#

I am writing a regex that validates timer input, timer only accepts 0 and between 5 and 120 min in both hour format (1:30) and min format (90).

It fails on "2:01", "2:59" and "0:01", "0:02", "0:03", "0:04", "0:1", "0:2", "0:3", "0:4"

import re
import pytest

pattern = re.compile("^(?:0|[5-9]|[1-9][0-9]|1[01][0-9]|120|[0-2]:[0-5]?[0-9])$")

@pytest.mark.parametrize("zeros", ("0", "0:0", "0:00"))
def test_valid_0_format(zeros):
    assert pattern.match(zeros)

@pytest.mark.parametrize("zeros", ("0:", "0::", "0:::", "0::0"))
def test_invalid_0_format(zeros):
    assert not pattern.match(zeros)

@pytest.mark.parametrize("minutes", range(5, 121))
def test_valid_min_format_from_5_to_120(minutes: int):
    assert pattern.match(f"{minutes}")

@pytest.mark.parametrize("time", ("3", "4"))
def test_invalid_min_format(time: str):
    assert not pattern.match(time)

@pytest.mark.parametrize("time", ("0:00", "1:00", "2:00"))
def test_valid_hour_min_format(time):
    assert pattern.match(time)

@pytest.mark.parametrize("hour", ("1:", "2:"))
def test_invalid_hour(hour):
    assert not pattern.match(hour)

@pytest.mark.parametrize("i", range(5, 121))
def test_valid_hour_format_from_5_to_120(i: int):
    hour, min = divmod(i, 60)
    assert pattern.match(f"{hour}:{min}")

@pytest.mark.parametrize("i", range(5, 121))
def test_valid_hour_format_from_5_to_120_leading_0(i: int):
    hour, min = divmod(i, 60)
    assert pattern.match(f"{hour}:{min:02}")

@pytest.mark.parametrize(
    "time",
    ("0:01", "0:02", "0:03", "0:04", "0:1", "0:2", "0:3", "0:4")
)
def test_invalid_hour_format_from_1_to_4(time):
    assert not pattern.match(time)

@pytest.mark.parametrize(
    "time",
    ("0:60", "1:60", "1:61", "2:01", "2:59", "3:0", "3:01")
)
def test_invalid_hour_min_format(time: str):
    assert not pattern.match(time)
graceful ferryBOT
#

@remote jolt

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

graceful ferryBOT
#

@remote jolt

Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.