English
Write a pattern matcher
Worked example and independent check
Test the anchored pattern ^cat$ on cat and scatter; expect exit codes 0 and 1. Test c.t and an optional letter next. Record input, exit status and the position of the match while stepping through your matcher.
Implementation stages
- CQ2 · In this stage, we'll handle the simplest regex possible: a single character. Example: a should match "apple", but not "dog".
- OQ2 · In this stage, we'll implement support for the \d character class. \d matches any digit. Example: \d should match "1", but not "a".
- MR9 · In this stage, we'll implement support for the \w character class. \w matches any alphanumeric character (a-z, A-Z, 0-9) and underscore _. Example: \w should match "foo101", but not "$!?".
- TL6 · In this stage, we'll add support for positive character groups. Positive character groups match any character that is present within a pair of square brackets. Example: [abc] should match "apple", but not "dog".
- RK3 · In this stage, we'll add support for negative character groups. Negative character groups match any character that is not present within a pair of square brackets. Example: [^abc] should match "dog", but not "cab" (since all characters are either "a", "b" or "c").
- SH9 · In this stage, we'll support patterns that combine the character classes we've seen so far. Examples: – \d apple should match "1 apple", but not "1 orange". – \d\d\d apple should match "100 apples", but not "1 apple". – \d \w\w\ws should match "3 dogs" and "4 cats" but not "1 dog" (because the "s" is not present at the end). This stage is significantly harder than the previous ones. You'll likely need to rework your implementation to process user input character-by-character instead of the whole line at once.
- RR8 · In this stage, we'll add support for ^, the Start of String or Line anchor. ^ doesn't match a character, it matches the start of a line. Example: ^log should match "log", but not "slog".
- AO7 · In this stage, we'll add support for $, the End of String or Line anchor. $ doesn't match a character, it matches the end of a line. Example: dog$ should match "dog", but not "dogs".
- FZ7 · In this stage, we'll add support for +, the one or more quantifier. Example: – a+ should match "apple" and "SaaS", but not "dog".
- NY8 · In this stage, we'll add support for ?, the zero or one quantifier (also known as the "optional" quantifier). Example: – dogs? should match "dogs" and "dog", but not "cat".
- ZB3 · In this stage, we'll add support for ., which matches any character. Example: – d.g should match "dog", but not "cog".
- ZM7 · In this stage, we'll add support for the | keyword, which allows combining multiple patterns in an either/or fashion. Example: – (cat|dog) should match "dog" and "cat", but not "apple".
SynQ discussion
Show SynQ the input, your prediction and what actually happened. Ask which intermediate value to inspect first.
Русский
Поиск по шаблону
Разбор примера и самостоятельная проверка
Проверьте ^cat$ на cat и scatter: ожидаются коды 0 и 1. Затем испытайте c.t и шаблон с необязательной буквой. При пошаговом разборе фиксируйте вход, код возврата и позицию совпадения.
Этапы реализации
- CQ2 · Найдите буквальный символ в строке и верните код 0 или 1.
- OQ2 · Распознайте класс цифр в шаблоне.
- MR9 · Распознайте класс букв, цифр и подчёркивания.
- TL6 · Проверьте совпадение с одним символом положительной группы.
- RK3 · Проверьте совпадение с символом вне отрицательной группы.
- SH9 · Совместите классы в последовательном шаблоне.
- RR8 · Привяжите поиск к началу строки через ^.
- AO7 · Привяжите поиск к концу строки через $.
- FZ7 · Через + примите одно или больше повторений предыдущего элемента.
- NY8 · Через ? примите ноль или одно вхождение.
- ZB3 · Точкой сопоставьте один произвольный символ.
- ZM7 · Обработайте альтернативы в группе и проверьте обе ветви.
Вопрос для SynQ
Покажите SynQ входные данные, ваш прогноз и фактический результат. Спросите, какое промежуточное значение проверить первым.
Қазақша
Үлгі бойынша іздеу
Мысал және өзіндік тексеру
^cat$ үлгісін cat және scatter жолдарымен тексеріңіз: кодтары 0 және 1. c.t мен міндетті емес әрпі бар үлгіні тексеріңіз. Іздеу барысында кірісті, қайтару кодын және сәйкестік орнын жазыңыз.
Іске асыру кезеңдері
- CQ2 · Жолдан таңбаны тура мәнімен іздеп, 0 немесе 1 кодын беріңіз.
- OQ2 · Үлгідегі цифрлар класын таныңыз.
- MR9 · Әріп, цифр және астыңғы сызық класын таныңыз.
- TL6 · Оң топтағы бір таңбаға сәйкестікті тексеріңіз.
- RK3 · Теріс топқа кірмейтін таңбаға сәйкестікті тексеріңіз.
- SH9 · Кластарды бірізді үлгіге біріктіріңіз.
- RR8 · ^ арқылы іздеуді жол басына бекітіңіз.
- AO7 · $ арқылы іздеуді жол соңына бекітіңіз.
- FZ7 · + арқылы алдыңғы элементтің бір немесе бірнеше қайталауын қабылдаңыз.
- NY8 · ? арқылы нөл немесе бір кездесуін қабылдаңыз.
- ZB3 · Нүкте арқылы бір еркін таңбаға сәйкестендіріңіз.
- ZM7 · Топтағы баламаларды өңдеп, екі тармағын да тексеріңіз.
SynQ-ға сұрақ
SynQ-ға кіріс деректі, өз болжамыңызды және нақты нәтижені көрсетіңіз. Алдымен қай аралық мәнді тексеру керегін сұраңыз.