Python regex
Rate quality
Private research annotation
Sign in to add a private research label or note.
- User
Python regex
Assistant
Python regex! Here's a comprehensive overview to get you started or to refresh your knowledge:
What is Regex?
Regular Expressions (regex) are a sequence of characters that define a search pattern used for matching, locating, and manipulating text. In Python, the
re(regular expression) module provides support for regex.Basic Concepts
- Patterns: The regex syntax used to match text.
- Matching: Finding text that fits the pattern.
- Groups: Sub-patterns within a pattern, useful for capturing specific parts of the match.
Python
reModuleImporting the Module
pythonimport reCommon Functions
re.search(pattern, string): Search for the first occurrence of the pattern in the string.re.match(pattern, string): Search for the pattern at the beginning of the string.re.findall(pattern, string): Return all non-overlapping matches of the pattern in the string as a list of strings.re.sub(pattern, repl, string): Replace occurrences of the pattern in the string with the replacement string.re.compile(pattern): Compile a pattern into a regex object, which can be used for matching using itsmatch(),search(), andfindall()methods.
Regex Patterns
Character Classes
- .: Any single character (except newline).
- ^: Start of the string.
- $: End of the string.
- |: OR operator.
- []: Set of characters (e.g.,
[abc]matches 'a', 'b', or 'c'). - [^ ]: Negated set of characters.
- \w: Word character (equivalent to
[a-zA-Z0-9_]). - \W: Non-word character.
- \d: Digit (equivalent to
[0-9]). - \D: Non-digit.
- \s: Whitespace character.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.