Regex (Regular Expression) is a pattern-matching syntax used in various programming languages and tools for searching and manipulating strings.

Regular Expressions can be used in various contexts, including:
- Text processing and manipulation
- Data validation and pattern matching
- Search and replace operations in text editors and IDEs
- Web scraping and data extraction
- Input validation in programming
Regex is supported in many programming languages, including Python, Perl, Java, JavaScript, and Ruby.
I have lived with regex since my Perl days. There are a lot of rules surrounding them and programmers pride themselves on writing hard-to-read code using regex. If you remember all of the rules, you can figure out what a regex means, but I have been using ChatGPT to explain them to me when I see them.
What does ‘$string =~ /(\w+)\s(\w+)/’ do in Perl?
Just ask ChatGPT.
The expression
$string =~ /(\w+)\s(\w+)/
in Perl is a regular expression pattern match operation. It tries to match the pattern(\w+)\s(\w+)
within the string$string
. If the pattern matches, the matched substrings are stored in special variables$1
,$2
, etc.The pattern
(\w+)\s(\w+)
consists of two sub-patterns(\w+)
separated by a white space\s
. Each sub-pattern matches one or more word characters\w
and the plus sign+
indicates to match one or more of the preceding expressions.For example, if the string
ChatGPT on What does ‘$string =~ /(\w+)\s(\w+)/’ do in Perl?$string
is"The quick brown fox"
, the match will be successful and$1
will contain the matched string"The"
, and$2
will contain"quick"
.
Effective Prompt Engineering for Regular Expressions and ChatGPT
Using a chatbot like ChatGPT effectively is all about writing good prompts. Context really helps the chatbot understand the prompt and how to return accurate results.
- Start prompt with the programing language
- Add Regex to the prompt
- Ask for example code
- Include a short description of the regex and specific rules (ignore case, match all occurrences, etc.)
- Ask for an explanation or not
- Ask for sample output or not
