Implement pattern matching from scratch. Start with literal characters and add regular-expression features with small, testable examples.
Set up your project
Choose a starter for your language. C · C++ · C# · Gleam · Go · Haskell · Java · JavaScript · Kotlin · Odin · PHP · Python · Ruby · Rust · TypeScript · Zig.
Use the examples in each stage to check your implementation locally. CodeCrafters operates its hosted runner separately.
- Starter templates
- Reference solutions
- Language environments
- Download the source snapshot (ZIP)
- Upstream test runner
Contents
- Core project · 12 stages
- Printing Matches · 2 stages
- Multiple Matches · 3 stages
- Highlighting · 5 stages
- File Search · 4 stages
- Quantifiers · 4 stages
- Backreferences · 3 stages
Core project
- Match a literal character
- Match digits
- Match word characters
- Positive Character Groups
- Negative Character Groups
- Combining Character Classes
- Start of string anchor
- End of string anchor
- Match one or more times
- Match zero or one times
- Wildcard
- Alternation
1. Match a literal character
grep searches text using regular expressions. In this stage, you’ll implement the simplest regex possible: matching a single literal character.
2. Match digits
In this stage, you’ll add support for the digit (\d) character class.
Character Classes
Character classes are special patterns in regular expressions that match specific sets of characters. Instead of matching a single literal character (like "a" or "3"), a character class matches any character from a defined group.
Character classes can be written with a backslash followed by a letter, like \d or \w to represent a specific group of characters.
The \d Character Class
The \d character class matches any single digit character (0-9).
For example:
\dshould match"3"\dshould match"foo101"\dshould not match"c"\dshould not match"Art"
When your pattern contains \d, you need to check if the input string contains at least one digit character.
Tests
The tester will execute your program like this:
$ echo -n "apple123" | ./your_program.sh -E "\d"
Your program must:
- Exit with code
0if it finds a digit in the input string. - Exit with code
1if it finds no digits in the input string.
Notes
- To learn how regexes work under the hood, you should build your own regex implementation from scratch instead of using your language’s built-in regex features.
3. Match word characters
In this stage, you’ll implement support for the word (\w) character class.
The \w Character Class
The \w character class matches any alphanumeric character (a-z, A-Z, 0-9) and underscore _.
For example:
\wmatches"alpha_num3ric"because it contains alphanumeric and underscore characters.\wmatches"foo101"because it contains letters and digits.\wdoes not match"$!?"because none of the symbols are word characters.
When your pattern contains \w, your program should check if the input string contains at least one word character.
Tests
The tester will execute your program like this:
$ echo -n "alpha_num3ric" | ./your_program.sh -E "\w"
Your program must:
- Exit with code
0if it finds a word character in the input string. - Exit with code
1if it finds no word characters in the input string.
Notes
- Underscore
_is included as it is considered part of a word in programming identifiers (e.g., variable and function names).
4. Positive Character Groups
In this stage, you’ll add support for positive character groups.
Positive Character Groups
Positive character groups match any character that appears within a pair of square brackets ([]).
Unlike the predefined character classes like \d and \w, positive character groups let you define your own custom set of characters to match.
The syntax looks like this: [characters].
For example:
[abc]matches"apple"because it containsa.[abc]matches"cab"because it containsa,b, andc.[abc]does not match"dog"because it contains neithera,b, norc.[123]matches"a1b2c3"because it contains1,2, and3.
When your pattern includes a character group (like [abc]), your program should check whether any of those characters appear in the input string.
Tests
The tester will execute your program like this:
$ echo -n "apple" | ./your_program.sh -E "[abc]"
Your program must:
- Exit with code
0if any of the characters in the group are found in the string. - Exit with code
1if none of the characters are found in the string.
5. Negative Character Groups
In this stage, you’ll add support for negative character groups.
Negative Character Groups
Negative character groups are the inverse of positive character groups. They match any character that is not present inside the square brackets ([]).
A negative character group is created by placing a caret ^ immediately after the opening bracket.
The syntax looks like this: [^characters].
For example:
[^abc]should match"cat", sincetis not in the seta,b, orc.[^abc]should not match"cab", since all the characters are in the set.
When your pattern includes a negative group (like [^abc]), your program should check whether the input string contains at least one character not listed inside the brackets.
Tests
The tester will execute your program like this:
$ echo -n "apple" | ./your_program.sh -E "[^abc]"
Your program must:
- Exit with code
0if the input contains any character that is not in the group. - Exit with code
1if all characters in the input are in the group.
6. Combining Character Classes
In this stage, you’ll add support for combining multiple character classes in a single pattern.
Matching Pattern Sequences
So far, you’ve been matching patterns with a single character class (\d, \w, [abc], etc.). Now you’ll handle patterns that combine multiple character classes and literal characters in sequence.
Here are some examples:
\d applematches"1 apple"(digit followed by" apple")\d appledoes not match"1 orange"(doesn’t end with"apple")\d\d\d applesmatches"I got 100 apples from the store"(found three digits followed by" apples")\d\d\d applesdoes not match"I got 1 apple from the store"(found only one digit and missing"s"in" apple")\d \w\w\wsmatches"4 cats"\d \w\w\wsdoes not match"1 dog"(missing the"s"at the end)
For this stage, you’ll likely need to rework your implementation to process the user input character-by-character instead of checking the whole line at once.
Tests
The tester will execute your program like this:
$ echo -n "1 apple" | ./your_program.sh -E "\d apple"
Your program must:
- Exit with code
0if the pattern matches the input string anywhere. - Exit with code
1if the pattern does not match the input string.
Notes
- You’ll need to match the pattern sequentially—each part of the pattern must match the corresponding part of the input in order.
- Think of your implementation as reading the input like a tape. It advances character by character as it tries to match the pattern.
- If you’re looking for ideas on how to approach this, “A Regular Expression Matcher” by Rob Pike is a great resource for inspiration. It demonstrates an elegant approach to building a regex matcher. However, you’re encouraged to work through the problem yourself first.
7. Start of string anchor
In this stage, you’ll add support for the start of string or line anchor (^).
Anchors
Anchors are a special type of regex pattern that specify positions in the string where a match must occur.
Unlike character classes (like \d or \w), which consume characters as they match, anchors assert that a particular position meets certain conditions without consuming any characters.
Start of String or Line Anchor (^)
The ^ anchor matches patterns at the start of an input string.
For example:
^logmatches"log"(pattern at start)^logmatches"logs"(starts with “log”)^logdoes not match"slog"(pattern not at start)^\d\d\dmatches"123abc"(three digits at start)
When your pattern starts with ^, your program should begin matching only from the first index of the input string, rather than searching for the pattern anywhere.
Tests
The tester will execute your program like this:
$ echo -n "log" | ./your_program.sh -E "^log"
Your program must:
- Exit with code
0if the input starts with the given pattern. - Exit with code
1if it doesn’t.
Notes
- Be careful to distinguish between
^as an anchor (at the start of a pattern) and^as negation (inside character groups like[^abc]). - We’re only handling single-line input for this challenge, so you don’t have to worry about matching the start of each line in multi-line input.
8. End of string anchor
In this stage, you’ll add support for the end of string or line anchor ($).
End of String or Line Anchor ($)
The $ anchor matches patterns at the very end of an input string.
For example:
dog$matches"dog"(pattern at end)dog$matches"hotdog"(ends with “dog”)dog$does not match"dogs"(pattern not at the end)\d\d\d$matches"abc123"(three digits at the end)\w\w\w$does not match"abc123@"(pattern not at the end)\w\w\w$matches"abc123cde"(three letters at the end)
Tests
The tester will execute your program like this:
$ echo -n "dog" | ./your_program.sh -E "dog$"
Your program must:
- Exit with code
0if the input ends with the given pattern. - Exit with code
1if it doesn’t.
Notes
- You can combine
^and$in the same pattern (e.g.,^dog$) to match the entire string exactly. - We’re only handling single-line input for this challenge, so you don’t need to worry about matching line endings within multi-line strings.
9. Match one or more times
In this stage, you’ll add support for the one or more quantifier (+).
Quantifiers
Quantifiers are special operators that specify how many times the preceding element should match.
Common quantifiers include:
+– matches one or more times?– matches zero or one time*– matches zero or more times
The One or More Quantifier (+)
The + quantifier matches the preceding character or character class one or more times. It’s a greedy quantifier, meaning it tries to match the element as many times as possible.
For example:
a+matches"apple"(one"a")a+matches"SaaS"(two consecutive"a"s)a+does not match"dog"(no"a")ca+tsmatches"cats"(one"a")ca+tsmatches"caats"(two"a")ca+tsdoes not match"cts"(needs at least one"a")\d+matches"123"(three digits)
Tests
The tester will execute your program like this:
$ echo -n "caats" | ./your_program.sh -E "ca+ts"
Your program must:
- Exit with code
0if the input matches the given pattern. - Exit with code
1if it doesn’t.
Notes
- The
+quantifier applies only to the immediately preceding element e.g., inca+ts, only the"a"is quantified, not the entire"ca". - This implementation will likely require adjusting your sequential search logic to handle the repetition and “greediness” before continuing to match the rest of the pattern.
10. Match zero or one times
In this stage, you’ll add support for the zero or one quantifier (?).
The ? Quantifier
The ? quantifier makes the preceding character or character class optional, meaning it can appear either once or not at all.
For example:
dogs?matches"dog"(zero"s")dogs?matches"dogs"(one"s")dogs?does not match"cat"(doesn’t match"dog"pattern)colou?rmatches"color"(zero"u")colou?rmatches"colour"(one"u")\d?matches"5"(one digit)\d?matches""(zero digits)
Tests
The tester will execute your program like this:
$ echo -n "dogs" | ./your_program.sh -E "dogs?"
Your program must:
- Exit with code
0if the input matches the given pattern. - Exit with code
1if it doesn’t.
11. Wildcard
In this stage, you’ll add support for the wildcard character.
The . Character
The . is a special character that matches any single character except a newline. It’s often called the “wildcard” because it acts as a placeholder for any character.
For example:
d.gmatches"dog"(.matches"o")d.gmatches"dag"(.matches"a")d.gmatches"d9g"(.matches"9")d.gdoes not match"cog"(doesn’t start with"d")d.gdoes not match"dg"(.requires exactly one character)...matches"cat"(three dots match any three characters).\d.matches"a1b"(one letter followed by a digit and another letter)
Tests
The tester will execute your program like this:
$ echo -n "dog" | ./your_program.sh -E "d.g"
Your program must:
- Exit with code
0if the input matches the given pattern. - Exit with code
1if it doesn’t.
12. Alternation
In this stage, you’ll add support for alternation.
The Alternation Operator (|)
The | (pipe) operator allows you to match one pattern or another.
Alternation is typically used within parentheses to group the alternatives: (pattern1|pattern2|pattern3).
Here are some examples:
(cat|dog)matches"cat"(matches first alternative)(cat|dog)matches"dog"(matches second alternative)(cat|dog)does not match"apple"(matches neither)(cat|dog)matches"doghouse"(contains “dog”)I like (cats|dogs)matches"I like cats"I like (cats|dogs)matches"I like dogs"(red|blue|green)matches"blue"
Tests
The tester will execute your program like this:
$ echo -n "cat" | ./your_program.sh -E "(cat|dog)"
Your program must:
- Exit with code
0if the input matches the given pattern. - Exit with code
1if it doesn’t.
Printing Matches
1. Print a single matching line
In this stage, you’ll add support for printing a single input line if it matches a pattern.
Printing Matching Lines
When grep finds a match, it prints the entire input line to standard output.
For example:
$ echo -n "apple" | ./your_program.sh -E "[^abc]"
apple
$ echo -n "cab" | ./your_program.sh -E "[^abc]"
$
Here, grep prints the line "apple" because it matches the pattern [^abc] (contains characters that aren’t a, b, or c). When grep receives "cab", it doesn’t match, so nothing is printed.
Grep also uses its exit code to indicate whether any matches were found:
- If the input line matches the pattern, the program exits with code
0(success). - If the input line does not match the pattern, the program exits with code
1(no match).
Tests
The tester will execute your program like this:
$ echo -n "dog" | ./your_program.sh -E "dog$"
The tester will verify that your program:
- Prints the input line to stdout when it matches.
- Prints nothing to stdout when it doesn’t match.
- Exits with code
0if the pattern matches. - Exits with code
1if the pattern doesn’t match.
Notes
- The tester will only test against a single input line. You don’t need to process multiple input lines in this stage. We’ll get to that in later stages.
2. Print multiple matching lines
In this stage, you’ll add support for printing multiple input lines if they match the pattern.
Printing Multiple Matching Lines
When grep receives multiple lines of input, it checks each line against the pattern and prints all lines that match.
For example:
$ echo -ne "line1\nline_two\nline3" | grep -E "\d"
line1
line3
Here, grep receives three lines of input. It prints "line1" and "line3" because they contain digits. "line_two" does not contain any digits, so it is not printed.
Grep’s exit code indicates whether any matches were found:
- If at least one line matches the pattern, the program exits with code
0. - If no lines match the pattern, the program exits with code
1.
Tests
The tester will execute your program like this:
$ echo -ne "first_line\n2nd_line\n3rd_line" | ./your_program.sh -E "\d"
The tester will verify that:
- Your program prints all matching lines to stdout (one per line).
- Your program prints nothing if no lines match.
- Your program exits with code
0if at least one line matches. - Your program exits with code
1if no lines match.
Multiple Matches
1. Print single match
In this stage, you’ll add support for printing a single matching text.
The -o Flag
The -o flag, also known as the only-matching flag, is used to print only the matching text in a separate line.
For example:
$ echo -ne "I have one cow" | grep -o -E 'cow'
cow
When grep finds a match with the -o flag:
- Extract the substring that matched the pattern
- Print only that substring (not the entire line)
- Exit with code
0
When no match is found:
- Print nothing
- Exit with code
1
Tests
The tester will execute your program like this:
$ echo -n "The king had 7 daughters" | ./your_program.sh -o -E "\d"
7
The tester will verify that:
- Your program prints only the matched text (not the entire line)
- Your program exits with code
0when a match is found - Your program prints nothing and exits with code
1when no match is found
Notes
- You only need to handle a single line of input and a single occurrence of the pattern. We’ll get to printing multiple matches and processing multiple lines in the later stages.
2. Print multiple matches
In this stage, you’ll add support for printing multiple matching texts from a single line.
Printing multiple matches
When a single line contains multiple matches for a pattern, the -o flag prints each match on its own line.
For example:
# The '\d' pattern matches 1 and 0 separately
$ echo -n "The king had 10 children" | grep -o -P '\d'
1
0
# The `\d\d` matches a pair of digits, so each pair (if found) is printed in its own line
$ echo -n "The king had 10 children" | grep -o -P '\d\d'
10
Tests
The tester will execute your program like this:
$ echo -e "jekyll and hyde" | ./your_program.sh -o -E "(jekyll|hyde)"
jekyll
hyde
The tester will verify that:
- All matches from the line are printed (one per line)
- Your program exits with code
0when at least one match is found - Your program prints nothing and exits with code
1when no matches are found
Notes
- You only need to handle the case of a single input line. We will get to processing multiple input lines in later stages.
3. Process multiple input lines
In this stage, you’ll add support for processing multiple input lines to print all matching texts.
Printing Multiple Matches from Multiple Lines
When an input contains multiple lines, the -o flag prints all matches from all lines, with each match on its own line.
For example:
# The '\d' pattern matches 1 and 0 separately in multiple lines
$ echo -ne "Line1: 10\nLine2: 42" | grep -o -P '\d'
1
1
0
2
4
2
# The `\d\d` matches a pair of digits, so each pair (if found) is printed in its own line
$ echo -ne "Line01: 50\nLine02: 42" | grep -o -P '\d\d'
01
50
02
42
The output appears in the same order as the input: all matches from line 1, then all matches from line 2, and so on.
Tests
The tester will execute your program like this:
$ echo -e "jekyll and hyde\nmickey mouse" | ./your_program.sh -o -E "(jekyll|hyde|mouse)"
jekyll
hyde
mouse
The tester will verify that:
- All matches from all lines are printed (one per line)
- Matches are printed in order (line by line, match by match)
- Your program exits with code
0when at least one match is found - Your program prints nothing and exits with code
1when no matches are found
Highlighting
- Highlight a single match
- Highlight multiple matches
- Highlight matches in multiple lines
- Disable highlighting
- Implement the auto color option
1. Highlight a single match
In this stage, you’ll add support for highlighting a single match.
The --color Flag
The --color flag tells grep to highlight matching text in its output. It accepts three values:
always: Always use colorsauto: Use colors only when outputting to a terminalnever: Never use colors
For this stage, you’ll implement the --color=always option.
Highlighting Matched Text
When a user passes the --color=always option, grep highlights the matched text by wrapping it with special formatting codes.
For example:
$ echo -n "I have 1 apple" | ./your_program.sh --color=always -E '\d'
I have 1 apple
The match (“1”) appears in bold red in the terminal output.
ANSI Escape Sequences
Grep uses ANSI escape sequences to add color to its output. These are special character sequences that terminals interpret as formatting commands rather than normal text.
By default, grep uses bold red for the matched text.
To highlight matched text, you need to:
- Insert an opening sequence before the matched text to add style and color formatting.
- Insert a closing sequence after the matched text to reset formatting back to normal.
You can make a matched text bold red by using the following ANSI escape sequences:
\033[01;31m
...
\033[m
Here’s a breakdown of the opening sequence (\033[01;31m):
| Component | Meaning |
|---|---|
\033 |
Escape character that introduces the ANSI control sequence |
[ |
Start marker for Select Graphic Rendition (SGR) parameters |
01;31 |
SGR codes: 01 = bold/bright text, 31 = red foreground color (separated by ;) |
m |
Terminates the SGR sequence |
For the closing sequence (\033[m):
| Component | Meaning |
|---|---|
\033 |
Escape character that introduces the ANSI control sequence |
[ |
Start marker for SGR parameters |
| (empty) | No parameters = reset all attributes to default |
m |
Terminates the SGR sequence |
For exmaple, to produce the following output:
hellomatchedworld
You can use any of the following sequences:
hello\033[01;31mmatched\033[mworld
# OR
hello\033[31;01mmatched\033[mworld
Tests
The tester will execute your program like this:
$ echo -n "I have 3 apples" | ./your_program.sh --color=always -E '\d'
I have 3 apples
If the input does not match the pattern, your program must:
- Exit with the code
1. - Exit with no printed output.
If the input text matches the pattern, your program must:
- Exit with the code
0. - Print the input text to the standard output.
- Highlight the matched text using grep’s default color.
Notes
- You only need to handle a single match in this stage. We’ll handle multiple matches in later stages.
- The order of the SGR codes doesn’t matter:
\033[31;01mand\033[01;31mboth produce the same bold red effect. - You’ll need to find the position of the match in the input string, then insert the opening sequence before it and the closing sequence after it.
2. Highlight multiple matches
In this stage, you’ll add support for highlighting multiple matches.
Highlighting Multiple Matches
Grep highlights all matching text it finds in a line.
For example:
$ echo -n "dogs and cats are pets" | grep --color=always -E '(dogs|cats)' dogs and cats are pets
Here, both dogs and cats are in bold red formatting.
For each match found in an input:
- Insert the opening ANSI sequence
\033[01;31mbefore the match - Insert the closing ANSI sequence
\033[mafter the match - Continue searching for the next match from where the previous match ended
Tests
The tester will execute your program like this:
$ echo -n "jekyll and hyde" | ./your_program.sh --color=always -E '(jekyll|hyde)' jekyll and hyde$ echo -n "2025" | ./your_program.sh --color=always -E '\d' 2025
If the input does not match the pattern, your program must:
- Exit with the code
1. - Exit with no printed output.
If the input text matches the pattern, your program must:
- Exit with the code
0. - Print the input text to the standard output.
- Highlight all the matched texts in the input with bold red formatting.
Notes
- You only need to handle the case of a single line. We’ll get to highlighting matches in multiple lines in the later stages.
- The order of the SGR codes doesn’t matter:
\033[31;01mand\033[01;31mboth produce the same bold red effect.
3. Highlight matches in multiple lines
In this stage, you’ll add support for highlighting matches in multiple lines.
Highlighting Matches in Multiple Lines
When grep processes multiple lines:
- Each line is processed independently
- Only lines that contain at least one match are printed
- All matches within each printed line are highlighted
For example:
$ echo -n "dogs and cats are pets\ndogs are nice" | grep --color=always -E '(dogs|cats)' dogs and cats are pets dogs are nice
Here, both lines are printed with their matches highlighted.
Tests
The tester will execute your program like this:
$ echo -e "Tiger in the wild\nBird in the sky" | ./your_program.sh --color=always -E '(Tiger|Bird)' Tiger in the wild Bird in the sky$ echo -e "Now: 2025\nNext: 2026" | ./your_program.sh --color=always -E '\d\d\d\d' Now: 2025 Next: 2026
If the input does not match the pattern, your program must:
- Exit with the code
1. - Exit with no printed output.
If the input text matches the pattern, your program must:
- Exit with the code
0. - Print each line that contains the match.
- Highlight every match in each line.
Notes
- The order of the SGR codes doesn’t matter:
\033[31;01mand\033[01;31mboth produce the same bold red effect.
4. Disable highlighting
In this stage, you’ll add support for disabling the highlighting in your grep implementation using the never coloring option.
The --color=never option
When a user passes the --color=never option:
- Matching lines are still printed.
- No ANSI escape sequences are added.
- The output is plain text without any formatting.
This is essentially the behavior from earlier stages before you added highlighting support.
For example:
$ echo -n "Sally has 3 parrots" | grep --color=never -E "par+ots?"
Sally has 3 parrots
Tests
The tester will execute your program like this:
$ echo -n "I have 5 vegetables" | grep --color=never -E '\d'
I have 5 vegetables
The tester will verify that:
- Matching lines are printed without any ANSI escape sequences.
- The output is plain text.
- Your program exits with code
0when a match is found. - Your program prints nothing and exits with code
1when no match is found.
5. Implement the auto color option
In this stage, you’ll add support for the --color=auto option.
The --color=auto Option
The --color=auto option makes grep automatically decide whether to use highlighting based on where the output is going:
- If the output stream is a TTY device, like a terminal, highlighting is enabled.
- If the output is piped to another command or redirected to a non-TTY device, highlighting is disabled.
For example, when you run grep in your terminal, stdout is connected to a TTY and highlighting is enabled:
$ echo -n "I have 3 cows" | ./your_program.sh --color=auto -E 'cows'
I have 3 cows
However, when you pipe the output to another command, stdout is no longer a TTY. In this case, grep detects this and disables highlighting:
$ echo -n "I have 3 apples" | ./your_program.sh --color=auto -E '\d' | hexdump -C
00000000 49 20 68 61 76 65 20 33 20 61 70 70 6c 65 73 |I have 3 apples|
0000000f
Notice there are no ANSI escape sequences in the output. It’s just plain text.
The same thing happens when you redirect output to a file:
$ echo -n "I have 4 apples" | ./your_program.sh --color=auto -E '\d' > output.txt
$ hexdump -C output.txt
00000000 49 20 68 61 76 65 20 34 20 61 70 70 6c 65 73 |I have 4 apples|
0000000f
The --color=auto option is helpful because ANSI escape sequences might look like gibberish when viewed in text files or processed by other programs. By detecting the output destination, grep can provide colored output for humans while keeping the output clean for programs.
Tests
The tester will execute your program in a terminal (TTY):
$ echo -n "I have 4 cats" | grep --color=auto -E 'cats'
I have 4 cats
If the input does not match the pattern, your program must:
- Exit with the code
1.
If the input text matches the pattern, your program must:
- Exit with the code
0. - Print the input text to the standard output.
- Highlight the matched text in the output.
The tester will also pipe your output to another command:
# Piping to another command
$ echo -n "He has 9 rabbits" | grep --color=auto -E '\d' | another_command
If the input does not match the pattern, your program must:
- Exit with the code
1. - Exit with no printed output.
If the input text matches the pattern, your program must:
- Exit with the code
0. - Print the input text to the standard output.
- Ensure the output text does not contain highlight matches with ANSI sequences.
Notes
- Most languages provide a way to check if stdout is a TTY:
isatty()in C,os.isatty(sys.stdout.fileno())in Python,System.console() != nullin Java, etc.
File Search
1. Search a single-line file
In this stage, you’ll add support for searching a single line of a file’s content.
File Search
When you give grep a file name as an argument, it searches through the lines in the file:
# This prints any lines that match search_pattern
$ grep -E "search_pattern" any_file.txt
This is a line that matches search_pattern
When searching the file, grep:
- Prints each matching line to stdout (the complete line, not just the matched part).
- Exits with code
0if any matching lines were found. - Exits with code
1if no matching lines were found.
For this stage, we’ll only handle files that contain a single line. We’ll handle multi-line files in later stages.
Tests
The tester will create test files and search them using your program:
# Create test file
$ echo "apple" > fruits.txt
# This must print the matched line to stdout and exit with code 0
$ ./your_program.sh -E "appl.*" fruits.txt
apple
# This must print nothing to stdout and exit with code 1
$ ./your_program.sh -E "carrot" fruits.txt
It will then verify that:
- All matching lines are printed to stdout.
- The exit code is
0if there are matching lines. - The exit code is
1if there are no matching lines.
Notes
- The file is guaranteed to exist and contain a single line.
- Your output should contain the full line that matches the pattern.
2. Search a multi-line file
In this stage, you’ll add support for searching the content of a file that contains multiple lines.
File Search with Multiple Lines
When searching through a file with multiple lines, grep processes each line individually:
# This prints any lines that match search_pattern
$ grep -E "search_pattern" multi_line_file.txt
This is a line that matches search_pattern
This is another line that matches search_pattern
Just like with single-line files, grep:
- Prints all matching lines to stdout.
- Exits with code
0if any matching lines were found. - Exits with code
1if no matching lines were found.
Tests
The tester will create test files and search them using your program:
# Create test file
$ echo "banana" > fruits.txt
$ echo "grape" >> fruits.txt
$ echo "blackberry" >> fruits.txt
$ echo "blueberry" >> fruits.txt
# This must print the matched lines to stdout and exit with code 0
$ ./your_program.sh -E ".*berry" fruits.txt
blackberry
blueberry
# This must print nothing to stdout and exit with code 1
$ ./your_program.sh -E "carrot" fruits.txt
It will then verify that:
- All matching lines are printed to stdout.
- The exit code is
0if there are matching lines. - The exit code is
1if there are no matching lines.
Notes
- You’ll need to read the file line by line and check each line independently against the pattern.
- The file is guaranteed to exist and contain multiple lines for this stage.
3. Search multiple files
In this stage, you’ll add support for searching the contents of multiple files.
Searching Multiple Files
When searching multiple files, grep processes each file individually:
# This prints any lines that match search_pattern from multiple files
$ grep -E "search_pattern" file1.txt file2.txt
file1.txt:This is a line that matches search_pattern
file2.txt:Another line that matches search_pattern
This behavior is similar to searching a single file, but with a few differences:
- All matching lines are printed to stdout with a
<filename>:prefix. - The program exits with code
0if any matching lines were found across all files. - The program exits with code
1if no matching lines were found in any file.
Tests
The tester will create test files and search them using your program:
# Create test files
$ echo "banana" > fruits.txt
$ echo "blueberry" >> fruits.txt
$ echo "broccoli" > vegetables.txt
$ echo "carrot" >> vegetables.txt
# This must print the matched lines to stdout and exit with code 0
$ ./your_program.sh -E "b.*$" fruits.txt vegetables.txt
fruits.txt:banana
fruits.txt:blueberry
vegetables.txt:broccoli
# This must print nothing to stdout and exit with code 1
$ ./your_program.sh -E "missing_fruit" fruits.txt vegetables.txt
It will then verify that:
- All matching lines are printed to stdout with filename prefixes.
- The exit code is
0if there are matching lines in any file. - The exit code is
1if there are no matching lines in any file.
4. Recursive search
In this stage, you’ll add support for searching through files in a nested directory with the -r flag.
Recursive Search
When grep is passed the -r flag, it searches through the given directory and its subdirectories recursively:
# This prints any lines that match search_pattern from multiple files
$ grep -r -E "search_pattern" directory/
directory/file1.txt:This is a line that matches search_pattern
directory/file2.txt:Another line that matches search_pattern
This behaviour is similar to searching multiple files:
- All matching lines are printed to stdout, but with a
<filepath>:prefix instead of<filename>:. - The program exits with code
0if it finds any matching line in any of the files. - The program exits with code
1if it does not find any matching lines in any file.
Tests
The tester will create test files in nested directories and search them using your program:
# Create test files
$ mkdir -p dir/subdir
$ echo "pear" > dir/fruits.txt
$ echo "strawberry" >> dir/fruits.txt
$ echo "celery" > dir/subdir/vegetables.txt
$ echo "carrot" >> dir/subdir/vegetables.txt
$ echo "cucumber" > dir/vegetables.txt
$ echo "corn" >> dir/vegetables.txt
# This must print the matched lines to stdout and exit with code 0
$ ./your_program.sh -r -E ".*er" dir/
dir/fruits.txt:strawberry
dir/subdir/vegetables.txt:celery
dir/vegetables.txt:cucumber
# This must print the matched lines to stdout and exit with code 0
$ ./your_program.sh -r -E ".*ar" dir/
dir/fruits.txt:pear
dir/subdir/vegetables.txt:carrot
# This must print nothing to stdout and exit with code 1
$ ./your_program.sh -r -E "missing_fruit" dir/
It will then verify that:
- All matching lines from all files in the directory tree are printed to stdout with filepath prefixes.
- The exit code is
0if there are matching lines in any file. - The exit code is
1if there are no matching lines in any file.
Notes
- GNU grep does not guarantee the order of its output. Instead, it processes files in the order they appear in the filesystem. Your
grepcan output matching lines in any order. - The filepath prefix should be relative to the directory passed as an argument (e.g.,
dir/subdir/file.txt, not justfile.txt).
Quantifiers
1. Match zero or more times
In this stage, you’ll add support for the zero or more quantifier (*).
The * Quantifier
The * quantifier matches the preceding element zero or more times. This means the element can be absent entirely or repeated any number of times.
For example:
ca*tmatches"ct"(zero"a"s)ca*tmatches"caaat"(three"a"s)ca*tdoes not match"dog"(no match for the pattern)k\d*tmatches"kt"(zero digits)k\d*tmatches"k1t"(one digit)k\d*tdoes not match"kabct"(has letters, not digits)k[abc]*tmatches"kt"(zero characters)k[abc]*tmatches"kat"(one character from the set)k[abc]*tmatches"kabct"(multiple characters from the set)k[abc]*tdoes not match"kaxyzt"(contains"x","y","z"which aren’t in[abc])
Tests
The tester will execute your program like this:
$ echo -n "apple" | ./your_program.sh -E "apple*"
Your program must:
- Exit with code
0if the input matches the pattern. - Exit with code
1if it doesn’t.
2. Match exactly n times
In this stage, you’ll add support for the {n} quantifier.
The {n} Quantifier
The {n} quantifier matches the preceding element exactly n times.
For example:
ca{3}tmatches"caaat"(exactly three"a"s)ca{3}tdoes not match"caat"(only two"a"s)ca{3}tdoes not match"caaaat"(too many"a"s)d\d{2}gmatches"d42g"(exactly two digits)d\d{2}gdoes not match"d1g(only one digit)d\d{2}gdoes not match"d123g"(too many digits)c[xyz]{4}wmatches"czyxzw"(exactly four characters from[xyz])c[xyz]{4}wdoes not match"cxyzw"(only three characters from[xyz])
Tests
The tester will execute your program like this:
$ echo -n "appleee" | ./your_program.sh -E "applee{2}"
Your program must:
- Exit with code
0if the input matches the pattern. - Exit with code
1if it doesn’t.
3. Match at least n times
In this stage, you’ll add support for the {n,} quantifier.
The {n,} Quantifier
The {n,} quantifier matches the preceding element at least n times. This means the element must appear n or more times, with no upper limit.
For example:
ca{2,}tmatches"caat"(exactly two"a"s)ca{2,}tmatches"caaaaat"(six"a"s)ca{2,}tdoes not match"cat"(only one"a")x\d{3,}ymatches"x9999y"(four digits)x\d{3,}ydoes not match"x42y"(only two digits)b[aeiou]{2,}rmatches"baeiour"(five vowels)b[aeiou]{2,}rdoes not match"bar"(only one vowel)
Tests
The tester will execute your program like this:
$ echo -n "caaat" | ./your_program.sh -E "ca{2,}t"
Your program must:
- Exit with code
0if the input matches the pattern. - Exit with code
1if it doesn’t.
4. Match between n and m times
In this stage, you’ll add support for the range quantifier ({n,m}).
The {n,m} quanitifier
The {n,m} quantifier matches the preceding element between n and m times (inclusive). This means the element must appear at least n times and at most m times.
For example:
ca{2,4}tmatches"caat"(two"a"s are within range)ca{2,4}tmatches"caaat"(three"a"s are within range)ca{2,4}tmatches"caaaat"(four"a"s are within range)ca{2,4}tdoes not match"caaaaat"(five"a"s are above the maximum)n\d{1,3}mmatches"n123m"(three digits are within range)n\d{1,3}mdoes not match"n1234m"(four digits are above the maximum)p[xyz]{2,3}qmatches"pzzzq"(three characters are within range)p[xyz]{2,3}qdoes not match"pxq"(one character is below the minimum)p[xyz]{2,3}qdoes not match"pxyzyq"(four characters are above the maximum)
Tests
The tester will execute your program like this:
$ echo -n "caaaat" | ./your_program.sh -E "ca{2,4}t"
Your program must:
- Exit with code
0if the input matches the pattern. - Exit with code
1if it doesn’t.
Backreferences
1. Single Backreference
In this stage, you’ll add support for backreferences.
Capturing Groups
So far, parentheses have been used for grouping alternatives with |. However, they can also be used to define a capturing group.
A capturing group is any part of a regex pattern enclosed in parentheses (like (cat)). When the pattern matches, the regex engine “captures” (stores) the specific text that matched within those parentheses.
Backreferences
A backreference lets you reuse a captured group in a regular expression. The syntax is \N where N is the group number:
\1refers to the first captured group\2refers to the second captured group- And so on…
For example:
(cat) and \1matches"cat and cat"(both are"cat")(cat) and \1does not match"cat and dog"("cat"≠"dog")(\w+) and \1matches"cat and cat"(\w+) and \1matches"dog and dog"(\w+) and \1does not match"cat and dog"(\d+)-\1matches"123-123"(same number repeated)
Tests
The tester will execute your program like this:
$ echo -n "cat and cat" | ./your_program.sh -E "(cat) and \1"
Your program must:
- Exit with code
0if the input matches the given pattern. - Exit with code
1if it doesn’t.
Notes
- You only need to focus on one backreference and one capturing group in this stage. We’ll get to handling multiple backreferences in later stages.
2. Multiple Backreferences
In this stage, you’ll add support for multiple backreferences.
Multiple Backreferences
In a previous stage, you handled a single backreference. Now you’ll extend this to support multiple captured groups and multiple backreferences in the same pattern.
Each set of parentheses creates a numbered capturing group, and you can reference any of them using \1, \2, \3, etc.
For example:
(\d+) (\w+) and \1 \2matches"3 red and 3 red"(\d+) (\w+) and \1 \2does not match"3 red and 4 red"(3≠4)(\d+) (\w+) and \1 \2does not match"3 red and 3 blue"(red≠blue)(cat) and (dog) are \2 and \1matches"cat and dog are dog and cat"(order reversed)(\w+)-(\w+)-\1-\2matches"foo-bar-foo-bar"
Tests
The tester will execute your program like this:
$ echo -n "3 red squares and 3 red circles" | ./your_program.sh -E "(\d+) (\w+) squares and \1 \2 circles"
Your program must:
- Exit with code
0if the input matches the pattern with all backreferences. - Exit with code
1if it doesn’t.
Notes
- You’ll need to track multiple captured groups and their matched text simultaneously. Consider using an array or map indexed by the group number.
- Each backreference must match the exact text captured by its corresponding group, not just any text that would match the group’s pattern.
- The backreferences can appear in any order and can be reused multiple times (e.g.,
\1can appear twice in the same pattern).
3. Nested Backreferences
In this stage, you’ll add support for nested backreferences.
Nested Capturing Groups
When the capturing groups are nested, each group still gets its own backreference based on the position of its opening parenthesis ((), counting from left to right.
For example, let’s break down the pattern ('(cat) and \2') is the same as \1:
- Group one (first
():'(cat) and \2' - Group two (second
():(cat) \2refers to group two, so it matches"cat"\1refers to group one, so it matches the entire"'cat and cat'"
An example of an input that would match this pattern is: "'cat and cat' is the same as 'cat and cat'"
Here are some more examples:
((dog)-\2)matches"dog-dog"(group two is"dog", group one is"dog-dog")((\w+) \2) and \1matches"cat cat and cat cat"
Tests
The tester will execute your program like this:
$ echo -n "'cat and cat' is the same as 'cat and cat'" | ./your_program.sh -E "('(cat) and \2') is the same as \1"
Your program must:
- Exit with code
0if the input matches the pattern with nested backreferences. - Exit with code
1if it doesn’t.
Source and licence
Stage material by CodeCrafters. Source snapshot · Original licence.
MIT License Copyright (c) 2022 CodeCrafters Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.