Regular Expressions
local graph
Chapter 4 — Regular Expressions
Section titled “Chapter 4 — Regular Expressions”Regular expressions, or regex, might seem daunting at first, but they’re an incredibly powerful tool for anyone working with text, especially in Bash scripting. This chapter is designed to ease you into the world of regex, starting from the basics and gradually moving to more complex patterns and techniques. Whether you’re looking to validate email addresses, search for specific patterns in log files, or automate text processing tasks, understanding regex is a game-changer. We’ll explore how to craft regex patterns, understand their structure, and apply them in practical scenarios. By the end of this chapter, you’ll not only be comfortable using regex but also appreciate how they can make your scripting tasks more efficient and versatile.
This chapter builds on the topics you learned about in the previous chapter. Regex is frequently used together with variables and conditional statements. For example, you’re likely going to use a while loop to read in a line of data from stdin or from a file and assign the data you read to a variable. Then, you’re going to perform a regex on the variable data, and finally make a decision using a conditional statement.
In this chapter, we’re going to cover the following main topics:
- The basics of regex
- Advanced regex patterns and techniques
- Demonstrating practical applications
- Regex tips and best practices
Technical requirements
Section titled “Technical requirements”It is helpful but not required to be able to install a Kali virtual machine, as stated in Chapter 1.
The code for this chapter can be found at https://github.com/PacktPublishing/Bash-Shell-Scripting-for-Pentesters/tree/main/Chapter04.
The basics of regex
Section titled “The basics of regex”At their core, regex is a method for searching, matching, and manipulating text. Think of them as a sophisticated search tool that goes beyond the capabilities of the standard search feature in your text editor or word processor. Regex allows you to define patterns in text, making it possible to perform complex searches and edits with relative ease.
Regex is incredibly versatile. Here are just a few examples of what they can be used for:
- Data validation: Ensuring that user input matches a specific format, such as email addresses or phone numbers
- Data extraction: Pulling specific pieces of information from a larger dataset, such as extracting all URLs from a web page
- Search and replace: Finding and replacing text in a document based on patterns rather than exact matches
The regex alphabet consists of characters and metacharacters. Characters are just what you think: letters, numbers, and symbols that you’re trying to find in your text. Metacharacters, on the other hand, are the special sauce of regex. They’re symbols that have a special meaning, helping to define patterns. Some common metacharacters include ., *, +, ?, ^, $, [], {n}, {n, m}, {n,}, (a|b), and =~.
In this section, I’ll be showing examples using the grep command. The grep command searches for patterns in files or piped input. You can learn more about grep by entering the man grep command.
The period (.) metacharacter matches any single character except newline, which is the end of a line and is represented by \n. One of the common ways I use . in regex is when parsing the output of a program and I want to eliminate blank lines. Just as. matches any character, when used by itself in a regex, its use removes any blank lines since there’s nothing to match. The following figure demonstrates that . matches any character. The matched text is highlighted in red font:

Figure 4.1 – Matching non-blank lines using the period metacharacter
As you can see, not only does the . metacharacter match any character (highlighted in red), but it also helps us to match only lines that aren’t blank.
The asterisk (*) metacharacter matches zero or more occurrences of the preceding element. Imagine that you have a text file named sample.txt with various lines of text, and you’re interested in finding lines that match the ho*p pattern. The pattern should match lines with hop, hoop, hooooop, and so on. The content of the sample.txt file is shown here:

Figure 4.2 – The content of the sample.txt file
Tip
You must use the grep command with the -E option for extended regex, which allows you to use the * metacharacter.
This command tells grep to search within sample.txt for lines that match the ho*p pattern: grep -E 'ho*p' sample.txt. The -E option is used to enable extended regex, which includes support for the * metacharacter, among other features. Otherwise, outside of a regex, * is called a glob character, as discussed in Chapter 2.
The plus (+) metacharacter matches one or more occurrences of the preceding element. For example, if you’re analyzing log files for errors, a pattern such as Error: + could help you find lines where Error: is followed by one or more spaces, indicating the start of an error message. Without the + metacharacter, you’d either miss cases with multiple spaces or waste time sifting through irrelevant data.
The question (?) metacharacter makes the preceding element optional. At its core, the ? metacharacter represents optionality. It tells the regex engine to match the preceding element zero or one time. Simply put, it means that the character or pattern right before? might be there, but it’s OK if it’s not.
This concept is easier to grasp with an example. Imagine that you’re tasked with processing log files. These logs follow a naming convention such as app-log-2024.txt, but sometimes, they include an extra identifier, such as app-log-2024-debug.txt. Using the ? metacharacter allows your script to be more flexible. A pattern such as app-log-2024(-debug)?.txt can match both filenames, ensuring your script works seamlessly across different log types.
The caret (^) metacharacter matches the start of a line. You might be wondering why you’d need to specify that something should be at the beginning of a line. It’s all about precision. In this example, if we didn’t use the ^ metacharacter and searched for DONE alone, we’d get any line containing DONE anywhere in the text – not just at the beginning. This could include lines where DONE appears in a note or reminder, not just as a task status marker.
The dollar ($) metacharacter matches the end of a line.
The following is an example of matching using $:

Figure 4.3 – Matching the end of a string using the $ metacharacter
Bracket expressions ([ ]) match any single character within the brackets. You can perform a logical NOT expression by making the ^ symbol the first character in the list. That would result in matching characters that are not on the list. For example, if you wanted to match vowel characters, an appropriate bracket expression would be [aeiou], whereas if you wanted to match consonants, you could use [^aeiou].
Range expressions are frequently used inside bracket expressions to save you the time and effort of typing all subsequent characters or numbers in a range. For example, instead of typing the letters a through z inside brackets, you can use [a-z] as a handy shortcut. Similarly, for numbers, you can use a range such as [1-10]. The following figure demonstrates how bracket expressions work:

Figure 4.4 – Examples of using bracket expressions
Bracket expressions are a valuable, time-saving regex feature!
The {n} metacharacter specifies that the preceding element is matched exactly n times. It can also be written as {n, m} or {n,}, meaning the preceding element is matched between n and n times, or is matched exactly n or more times, respectively. Let’s look at how this can be used:

Figure 4.5 – An example showing how to match n or more times
The preceding figure shows that I specified that it must match 3 or more times for the o character. The word hoooop was the only match. Note that I had to include the -E argument in grep to enable extended regex capability, and had to escape the brackets with a backslash.
The (a|b) metacharacter matches either a or b.
The =~ match operator is typically used inside scripts. Let’s discuss the basic example shown in the following figure:

Figure 4.6 – An example demonstrating the match operator
If the string on the left-hand side of the =~ operator matches the regex on the right, the expression evaluates to true, and the exit status of the [[ ]] bracket expression is 0 (zero). In Bash shell scripting, an exit status of 0 signifies success or true. An exit value of anything other than 0 signifies failure or false.
In Bash scripting, && and || are logical operators that are used within conditional expressions to combine multiple commands or conditions. Their usage is tied to the exit status of commands. Applied to the previous figure, if the match pattern finds a match on the input expression, it results in an exit status of 0, or true. If the string doesn’t match the regex, the expression evaluates to false, and the exit status of the [[ ]] expression is 1 (an exit status of 1 signifies failure or false). The && operator passes the exit status to the following || expression, which can be thought of as true or false. If the expression was true, the statement on the left, echo Match found!, is executed. If false, the statement on the right, echo "No match", is executed.
Now that you’re familiar with metacharacters, let’s explore character classes, which provide handy shortcuts when using the bracket expressions we just covered.
Using character classes
Section titled “Using character classes”When used inside bracket expressions, character classes are a handy shortcut that simplifies regex:
[:alpha:]: Alphabet characters[:alnum:]: Alphanumeric characters[:digit:]: The numbers 0 through 9[:blank:]: Spaces and tabs[:cntrl:]: Control characters[:lower:]: Lowercase letters[:upper:]: Uppercase letters[:punct:]: Punctuation characters[:space:]: Space characters, including space, tab, newline, vertical tab, form feed, and carriage return
Tip
Character classes must be enclosed inside bracket expressions – for example, [[:alpha:]].
Character classes are a time-saving shorthand that greatly simplifies the process of creating regex.
Flags – modifying your search
Section titled “Flags – modifying your search”Regex allows you to modify your search with flags. These are usually single letters that change how the regex engine interprets your pattern. Here are some examples:
i: Makes the search case-insensitiveg: Performs a global search (finds all matches rather than stopping after the first match)m: Multiline mode (changes the behavior of^and$to match the start and end of lines rather than the whole string)
This is not an exhaustive list. See https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html for more information. These flags can be used alone or in combination, depending on the requirements of the regex operation. The way to apply these flags varies slightly between tools, but they are usually appended to the regex pattern. Since their use is tool-dependent, I’ll show you examples of how they can be used when I present practical examples later in this chapter.
Now that you understand the basics of regex, let’s review some examples showing how they work.
Applying basic regex examples
Section titled “Applying basic regex examples”This example simply uses grep to match on the letter t. By default, grep performs a global search. Therefore, the g flag isn’t necessary:

Figure 4.7 – A basic grep on the t character
This example matches all vowels:

Figure 4.8 – A pattern that matches all vowels
This example matches all consonants. Remember that the ^ symbol takes on a different meaning inside of brackets. This essentially means that it matches any character not in the list:

Figure 4.9 – A pattern that matches all consonants
Now, I’ll show you a slightly more advanced example. Can you spot the difference between the following two examples?

Figure 4.10 – Two patterns used to demonstrate a subtle difference
The first pattern matches t followed by zero or more characters that are not w. It’s important to note that * applies to the [^w] part of the pattern, allowing for any sequence of characters that does not start with w immediately following t. Therefore, it matches everything, including the spaces, starting with t in told, and continues through the end of the input.
The second pattern specifically looks for t followed by a single character that is not w, and then zero or more alphabetic characters. The inclusion of [[:alpha:]]* after [^w] means that after finding t followed by any non- w character, it matches only if the following characters are alphabetic.
Tip
The examples in Figure 4*.10* show a backslash character escaping the asterisk. A small number of characters have special meaning. The following characters must be escaped with a backslash: [\^$.|?*+().
Now that you understand the basics, let’s get a taste of some advanced regex concepts.
Advanced regex patterns and techniques
Section titled “Advanced regex patterns and techniques”In regex, using capture groups is like putting a part of your pattern into a box. Everything inside this box is treated as a single unit. You can apply quantifiers to it, look for repetitions, or even extract information from it. In Bash, you use parentheses, (), to create these groups.
Grouping isn’t just about treating parts of your pattern as a single unit; it’s also about capturing information. When you group part of a regex pattern, Bash remembers what text matched that part of the pattern. This is incredibly useful for extracting information from strings.
Let’s say you’re working with log files and you want to extract timestamps. Your log lines might look something like this: 2023-04-01 12:00:00 Error: Something went wrong. A regex pattern to match the timestamp could be (\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}). Here, \d matches any digit, and {n} specifies how many times that element should repeat. The entire timestamp pattern is grouped, so you can extract it from the string easily.
Let’s look at some practical examples to help you solidify your understanding of capture groups.
Practical example – extracting data using regex
Section titled “Practical example – extracting data using regex”Imagine you’re tasked with extracting usernames and their corresponding email addresses from a list. The list looks something like this:
john_doe: [email protected]jane_smith: [email protected]You could use the following regex pattern to match and extract the usernames and email addresses:
([a-zA-Z0-9_]+): ([a-zA-Z0-9_.]+@[a-zA-Z0-9_.]+)Here, [a-zA-Z0-9_]+ matches one or more alphanumeric characters or underscores (the username), and [a-zA-Z0-9_.]+@[a-zA-Z0-9_.]+ matches the email addresses. By grouping them, you can extract both the username and the email address separately.
For example, let’s say you have I love apples and I love oranges as a string and you want to find every instance of I love. In regex, you could write this pattern as (I love). This tells Bash to treat I love as a single unit.
Regex grouping in Bash might seem complex at first glance, but once you understand the basics, it opens up a world of possibilities for string manipulation and data extraction. By breaking down patterns into manageable groups, you can simplify your scripts and make them more efficient. Remember, practice makes perfect. Start experimenting with regex grouping in your Bash scripts, and you’ll soon wonder how you ever managed without it.
Next, we’ll expand on regex grouping by showing you how to use alternations to make your capture groups more powerful and flexible.
Utilizing alternations
Section titled “Utilizing alternations”Regex alternation is represented by the pipe symbol (|), which functions similarly to a logical OR. It allows you to specify multiple patterns within the same regex, offering a way to match one thing or another. Think of it as telling your script, “Hey, if you see this or that, consider it a match.”
Let’s say you’re writing a script that needs to process files with specific extensions. You’re interested in .txt and .log files but want to handle them using a single regex. Here’s how you could do it:
#!/usr/bin/env bashfilename="example.txt"if [[ $filename =~ \.(txt|log)$ ]]; then echo "File is either a .txt or .log file."else echo "File is not a .txt or .log file."fiThis example code can be found in the ch04_regex_01.sh file in this chapter’s folder.
Running this example provides the following output:
$ bash ch04_regex_01.shFile is either a .txt or .log file.In this example, (txt|log\)$ is the regex pattern. The pipe symbol, |, separates the two alternatives, txt and log, while the backslashes, \, are used to escape characters that have special meanings in regex. The dollar sign, $, ensures that the pattern matches the end of the string, preventing false positives on files such as example.txt.bak.
You might be wondering why bother with alternation when you could just write separate conditions for each case. The answer lies in simplicity and efficiency. Using alternation, you can consolidate multiple conditions into a single line of code, making your scripts cleaner and easier to maintain.
In scenarios where you’re matching against a long list of possibilities, alternation can significantly reduce the complexity of your code. Instead of having an unwieldy series of if statements or a cumbersome case statement, you can list all your options in one place.
While alternation is powerful, it’s essential to use it wisely to avoid pitfalls. Here are a couple of tips to keep in mind:
- Be specific: Regex patterns can sometimes match more than you intend. To prevent unexpected behavior, make your patterns as specific as possible.
- Testing: Always test your regex patterns with various inputs to ensure they behave as expected. Tools such as
grepand online regex testers (https://regex101.com) can be invaluable for this.
Regex alternations in Bash scripting are like having a secret weapon in your arsenal. They allow you to write more concise, readable, and maintainable code by simplifying complex pattern-matching logic. Whether you’re a seasoned scripter or just starting, mastering alternations will undoubtedly make your scripting journey smoother and more enjoyable.
Remember, the key to effective scripting is not just knowing what tools are available but understanding how to use them wisely. With regex alternations, you’re well-equipped to tackle a wide range of string-matching challenges.
Now that you have a good grasp of how regex works, let’s explore some practical regex applications.
Demonstrating practical applications
Section titled “Demonstrating practical applications”Here, I’m using various variables and arrays that were introduced in previous chapters. Let’s put this into practice with the following Bash script:

Figure 4.11 – Introducing BASH_REMATCH in a practical application
This example code can be found in the ch04_regex_02.sh file in this chapter’s folder. In this script, I declared the user_list variable on line 3. On line 6, I declared the pattern variable. On line 8, I started a while loop that reads each line of data from the $ user_list variable.
On line 9, I used the match operator, =~, to compare each line ($line) against our regex pattern ($pattern). These are referred to by the $line and $pattern variables, which are declared. When you use the match operator, the string on the left (represented by the $line variable) is matched against the regex pattern on the right. If the pattern matches, the expression returns true (0); otherwise, it returns false (1).
First, the pattern captures a username using the relevant capture group: ([a-zA-Z0-9_]+). Remember, a capture group consists of parenthesis, (), surrounding a regex. Inside the capture group, we have a bracket expression that will match all alphanumeric characters, plus an underscore to match usernames. The second capture group matches an email address.
If a line matches, Bash populates an array called BASH_REMATCH with the captured groups. Here, BASH_REMATCH[1] contains the first captured group (the username), and BASH_REMATCH[2] contains the second group (the email address). Then, we print these out:
~ $ bash ch04_regex_02.shUsername: john_doe, Email: [email protected]Username: jane_smith, Email: [email protected]Did you spot where I could have made the capture groups easier to read and write? The first capture group, ([a-zA-Z0-9_]+), could have been simplified to ([[:alnum:]_]+), and the second capture group, ([a-zA-Z0-9_.]+@[a-zA-Z0-9_.]+), could have been simplified to ([[alnum]_.]+@[[:alnum:]_.]+).
Matching IP addresses with grep
Section titled “Matching IP addresses with grep”In this example, we’re going to look at a practical case involving a port scan to locate IP addresses with specific ports open. This is a common pentest task that is frequently used to produce a list of hosts to use with subsequent targeted scans, or for producing a list of affected hosts for a pentest finding.
Since this involves scanning your local network, make sure you have permission to scan the network if you don’t own it. I’ve included a sample Nmap scan file from my lab for your convenience in this book’s GitHub repository: test_nmap.gnmap.
Use the following Nmap command to scan the network, replacing the network address with one applicable to your network address:
nmap -oG test.gnmap 10.1.0.0/24The scan command’s options specify greppable output, -oG, the output filename, test_nmap.gnmap, followed by the network address.
In my scan, one line of the scan that’s output from the test_nmap.gnmap file looks like this:
Host: 10.1.0.1 () Ports: 53/open/tcp//domain///, 80/open/tcp//http///, 443/open/tcp//https///Next, we want to identify any host IP addresses with open http or https service ports. Execute the following command in the same directory as the test_nmap.gnmap file:
grep /open/tcp//http test_nmap.gnmap | grep -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b"This example code can be found in the ch04_regex_03.sh file in this chapter’s folder.
The preceding command uses grep to search for a regex of the literal (no metacharacters) text, /open/tcp//http. The output of that command is the full line of text of every line that includes that string. The pipe character, |, simply connects the output (stdout) of the first process with the input (stdin) of the next process. Then, the -oE arguments are provided with the grep command. The -o option means to output only the matching text instead of the full line, and the -E option enables the extended regex feature. Finally, the regex pattern for an IP address ends the command. The following output is produced by this command:
~ $ grep /open/tcp//http test_nmap.gnmap | grep -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b"10.1.0.110.1.0.410.1.0.610.1.0.710.1.0.13The pipe character’s use to redirect output to the input of another process is a powerful feature that we’ll be using frequently in later chapters.
Using handy grep flags
Section titled “Using handy grep flags”While these grep flags are pretty simple, they’re also very handy. I use them frequently and want to share them with you.
Something that I frequently do on internal network pentest is use any credentials that I’ve obtained to enumerate file shares that can be accessed with those credentials. In this example, I’m using NetExec to check for SMB file shares that are accessible with the credentials I have. You can find NetExec at https://github.com/Pennyw0rth/NetExec.
The following figure shows the output of a NetExec SMB file share enumeration scan:

Figure 4.12 – NetExec SMB share enumeration scan
The scan output was saved to a file, nxc.log. Let’s imagine that I’ve run this scan on a large network with hundreds or even thousands of hosts and I want to focus on finding those shares where I can either read or write to the share, but I don’t want to see any of the IPC$ or PRINT$ shares.
While there are regex patterns that could reasonably work here to match a combination of READ / WRITE, we want to keep this simple so that we don’t have to refer to our notes. The following command can accomplish this goal:

Figure 4.13 – Our grep flags simplify the task
This example code can be found in the ch04_regex_04.sh file in this chapter’s folder. Let’s break down the sequence of commands:
cat nxc.log: This prints the output of thenxc.logfile.|: This connects the output of thecatcommand to the input of thegrepcommand.grep -e READ -e WRITE: Thegrep-eflag specifies a pattern. More than one pattern can be used if you include additional-eflags. This will match if either or both of the words are found.grep -v …: Thegrep-vflag means invert the match. This is similar to a logicalNOTexpression. In other words, filter out anything that matches this expression.
You will use these patterns frequently in your pentest career.
Redacting IP addresses
Section titled “Redacting IP addresses”While the following example demonstrates redacting IP addresses using the sed (stream editor) command, it can be adapted to other cases of mass editing text in a file or input stream.
Let’s imagine that you want to redact the IP addresses in the test_nmap.gnmap file before you share it with someone. Again, we’ll use the regex for an IP address. However, this time, we’ll pipe the output to sed and redact all IP addresses. Run the following command in your Terminal:
sed -E 's/([0-9]{1,3}\.){3}[0-9]{1,3}/REDACTED_IP/g' test_nmap.gnmapThis example code can be found in the ch04_regex_05.sh file in this chapter’s folder. The output should show that every IP address in the file has been redacted.
So, what does this sed command do?
- The
-Eoption enables extended regex. - The command after
sedis enclosed in single quotes. - After the
sedcommand and arguments, you’ll see a pattern similar to's/MATCH/REPLACE/g'. - The
soption means search for anything (literal text or regex) between the next/characters (theMATCHtext). - Replace the matched text with the pattern between the next set of slash (
/) characters (theREPLACEtext). - The
gflag means to make it aglobalsearch and replace every occurrence. Otherwise, if the regex or literal string was matched twice on the same line, it would only perform the substitution on the first match.
In this example, we didn’t edit the original file in place. We only edited the text output to the screen. There are two ways we could have edited and saved the text: by including the sed -i flag or by redirecting the output to a file.
In the first case, edit the file in place by adding the sed - i flag:
sed -iE 's/([0-9]{1,3}\.){3}[0-9]{1,3}/REDACTED_IP/g' test_nmap.gnmapThis example code can be found in the ch04_regex_06.sh file in this chapter’s folder. The other option omits the -i flag. It will preserve the original file and redirect the edited text to a new file:
sed -E 's/([0-9]{1,3}\.){3}[0-9]{1,3}/REDACTED_IP/g' test_nmap.gnmap > new_test_nmap.gnmapThis example code can be found in the ch04_regex_07.sh file in this chapter’s folder. The preceding command uses the > character to redirect the output to the filename that follows.
Tip
When using the > character to redirect output (stdout) to a file, it will overwrite the file if it exists. To append to an existing file instead of overwriting it, utilize >> in the command.
Next, let’s examine using awk for regex matching. Awk is much more than just a tool for regex; it’s a full-fledged programming language. Where it shines is when you’re sifting through tabular data (columns, tab, and comma-separated data). Before learning awk, I mistakenly believed it to be too complex and I would chain together multiple tools to do the same job, ultimately putting in more work than I would if I just used awk. I’ll be a bit brief in this chapter and stick to a few quick examples because we’ll be going more in depth in the next chapter.
Awk programs can be a single line for quick one-off scripts, though they can be used in files for more complex use cases. The format of a one-line awk script is awk 'pattern {action}'. Either pattern or action may be omitted, but not both.
The default field separator is any whitespace, such as spaces or tabs. Multiple whitespace characters are treated as a single unit. This is very helpful as I used to use tr -s ' ' to squeeze or combine multiple spaces into one before learning awk.
Before diving into our first awk example, let’s take a minute to understand common awk terms:
Record: Each line of an input file is referred to as a record.Field: Each column is a field.$n: Each field (column). The whole record (line) is$0, the first field is$1, and so on.$NF: The number of fields in a record. It can also be used to refer to the last field.$NR: The number of records so far.-F: A field separator; this is a space by default. Remember, any number of consecutive spaces are combined. So, if the first two fields are separated by one or multiple spaces,$1and$2still refer to the first and second fields (columns).
In the following figure, you can see the output of the ps -ef command on my system. This is the data I’ll be using in the following examples:

Figure 4.14 – System processes are shown when using the ps command
In our first awk example, I’m simply going to print each record (line):

Figure 4.15 – Printing the whole record using $0
This example code can be found in the ch04_regex_08.sh file in this chapter’s folder.
Next, we’re going to look at a more advanced example. In the following figure, I’m using a pattern and action. This example will match any process with a UID of author and print the CMD ($8, or the 8th field):

Figure 4.16 – Printing the CMD of any process owned by author
This example code can be found in the ch04_regex_09.sh file in this chapter’s folder.
In our final awk example, we’re going to examine how to use regex and print the output with a custom separator:

Figure 4.17 – Using a regex and printing the custom output with awk
This example code can be found in the ch04_regex_10.sh file in this chapter’s folder. In the preceding example, the regex in the pattern matches anything in the eighth field that starts with [irq/, followed by exactly two digits, followed by -pciehp]. For any matching records, the action prints the first and eighth fields, separated by ---> instead of the default space.
We’ve only scratched the surface of how to use awk. However, the concepts demonstrated here will solve the most common scripting tasks. We’ll explore this subject more in the next chapter.
Regex tips and best practices
Section titled “Regex tips and best practices”The following tips will help guide you through creating complex regex patterns:
- Start small: Begin with simple patterns and gradually introduce more complexity.
- Practice: Use online regex testers to experiment with different patterns and flags.
- Break it down: When faced with a complex pattern, break it down into smaller parts to understand each component.
- Refer to documentation: Keep a cheat sheet or reference guide handy until you’re more comfortable with common patterns and metacharacters. While there are plenty of regex cheat sheets to be found online, I suggest that you make your own while reading this book and experimenting. I find that the act of making notes helps me commit difficult concepts to memory.
Summary
Section titled “Summary”In this chapter, we provided an introduction to regex, followed by more advanced topics, including metacharacters and capture groups. Finally, we learned how to apply these techniques to real-world applications of Bash scripting that you will find useful for pentesting.
Regex doesn’t have to be intimidating. With a basic understanding of characters, metacharacters, and flags, you’re well on your way to harnessing their power. Whether you’re editing text, analyzing data, or validating user input, regex can be an invaluable tool in your toolkit. Remember, like any skill, proficiency comes with practice. So, dive in, start experimenting, and soon they will become easy with a bit of practice.
In the next chapter, we’ll combine the regex concepts we learned in this chapter with common text parsing tools so that we can focus on common cybersecurity and pentesting tasks.