Go Regular Expressions
Regular expressions (regex) are a way to search for patterns in text. Go provides the regexp package for this.
Basic Example
Common Functions
| Function | What it does |
|---|---|
MatchString |
Returns true if pattern is found. |
FindString |
Returns the first match found. |
FindAllString |
Returns all matches found in a slice. |
ReplaceAllString |
Replaces all matches with a new string. |
Split |
Splits a string using the regex as a separator. |
Submatches (Groups)
Use parentheses () to capture specific parts of a match.
Why use Regular Expressions?
- Validation: Check if a string is a valid email, phone number, or password.
- Extraction: Pull specific data (like dates or IP addresses) out of logs.
- Transformation: Clean up or reformat text.
Performance Tip
Always pre-compile your regex using regexp.MustCompile if you're going to use it more than once (e.g., inside a loop). Compiling a regex is expensive!