Check if a string matches a regex in Bash script


How to Check if a String Matches a Regex in Bash Script 💻🔍
So, you have a date input in the yyyymmdd
format, and you want to make sure it's a valid date. The good news is that you can use regular expressions (regex) in your Bash script to accomplish this task. 🎉
The Regular Expression 🔤🔍
You mentioned that you were trying to use the following regex pattern: [0-9]\{\8}
. However, there is a small issue with this pattern. In Bash, curly braces {} are used for range repetition, but the correct syntax for matching exactly eight digits is [0-9]{8}
. Each digit is represented by [0-9]
, and the number in curly braces specifies the exact number of times it should repeat.
Using the [[ ]]
Construct in Bash 🖥️🔨
To check if a string matches a regex pattern in Bash, you can make use of the double square bracket [[ ]]
construct. This construct provides more features and flexibility compared to the single square bracket [ ]
construct.
Here's an example of how you can use the [[ ]]
construct with your regex pattern to check if a string is a valid date:
#!/bin/bash
input="20211231" # Your input date here
if [[ $input =~ ^[0-9]{8}$ ]]; then
echo "Valid date"
else
echo "Invalid date"
fi
In this example, we initialize the input
variable with your date input. Then, we use the =~
operator to match the value of input
against the regex pattern ^[0-9]{8}$
.
The
^
and$
symbols denote the start and end of the string, respectively, ensuring that the whole string is matched.The
[[ ]]
construct automatically treats the right side of=~
as a regex pattern.
If the input matches the pattern, "Valid date" will be printed. Otherwise, "Invalid date" will be displayed.
More Regex Examples 🌟✨
Now that you have a basic understanding of how to use regex in Bash, let's explore a few more examples to further illustrate its usage:
Checking for a valid email address:
email="user@example.com" if [[ $email =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then echo "Valid email address" else echo "Invalid email address" fi
Confirming a properly formatted URL:
url="https://example.com" if [[ $url =~ ^(https?|ftp)://[^\s/$.?#].[^\s]*$ ]]; then echo "Valid URL" else echo "Invalid URL" fi
These examples demonstrate the power and versatility of regex in Bash. With regex, you can perform complex pattern matching and validation.
Your Turn! 🚀📝
Regex can be a game-changer when it comes to pattern matching and validation in Bash scripts. Now it's your turn to apply this knowledge to your own scripts.
If you have any questions or issues, feel free to ask in the comments below. I'm here to help! Let's dive into the world of regex together! 🤩🔍
Further Reading 📚🔖
Don't forget to share this post with your fellow Bash enthusiasts! Happy coding! 💻🎉
Take Your Tech Career to the Next Level
Our application tracking tool helps you manage your job search effectively. Stay organized, track your progress, and land your dream tech job faster.
