Python Regex Interview Questions
Python Regex Interview Questions
To match a phone number format such as (XXX) XXX-XXXX using Python regular expressions, the following pattern can be employed: '\(\d{3}\) \d{3}-\d{4}'. Here, `\(\d{3}\)` matches the area code within parentheses containing exactly 3 digits, `\d{3}` matches the next three digits, followed by a hyphen with `\d{4}` for the final four digits. This pattern ensures the phone number adheres to the specified format, verifying and extracting correctly formatted phone numbers from the text .
The \b (word boundary) anchor in regular expressions indicates a position between a word character (\w) and a non-word character (\W) or vice versa. It's used to ensure that the match is found at the beginning or end of a word, thereby preventing partial matches within longer words. For example, the pattern '\bword\b' would match 'word' in 'a word of' but not in 'sword', making it invaluable for precise text searches where standalone terms are required without suffixes or prefixes .
The '^' and '$' characters in regular expressions are anchors. '^' asserts the position at the start of a line, ensuring that the specified pattern must occur at the beginning of the string (or line in multi-line mode). Conversely, '$' asserts the position at the end of a line, indicating that the pattern must occur at the end. These characters are crucial for precise pattern matching since they restrict where matches can occur within the target string, especially useful for exact line or whole-string validation such as line formatting or verifying whole strings in scripts .
Validating an email address using regular expressions in Python typically involves constructing a pattern that accounts for the components of valid email syntax. A basic pattern could be: `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`, which ensures there is a local part before the '@', a domain following it, and a top-level domain of at least two letters. This pattern ensures that the email address adheres to the commonly accepted structure .
Grouping in regular expressions, denoted by parentheses, is used to create sub-patterns, which can be treated as a single unit. This is particularly useful for extracting or manipulating parts of the matched text. By enclosing parts of a regex pattern in parentheses, you create capture groups which can then be accessed using methods like `group()` and `groups()`. For example, in the expression `(\d+)-(\d+)`, two groups are defined: one for digits before the dash and one for digits after, which can separately be extracted and used in the Python code .
The primary differences between re.match(), re.search(), and re.findall() in Python are as follows: re.match() checks for a match only at the beginning of the string, meaning it returns a match object if the pattern is present at the start. In contrast, re.search() scans through the entire string to locate the first occurrence of the pattern and returns a match object when found. Meanwhile, re.findall() returns all non-overlapping matches of the pattern in the string as a list of strings, allowing for multiple matches .
Special characters in regular expressions serve to define the search pattern more precisely. They include symbols like '.' (dot), which matches any single character except a newline, '*' (asterisk), which matches 0 or more occurrences of the preceding element, and '+' (plus), which matches 1 or more occurrences. The character '?' makes a quantifier non-greedy, and '^' signifies the start of a string, whereas '$' signifies the end. Characters like '[' and ']' define a character class, and '\' is used to escape special characters .
The re.sub() method in Python regular expressions is used to replace occurrences of a specified pattern within a string with a replacement text. The method signature is `re.sub(pattern, replacement, string, count=0, flags=0)`, allowing for optional arguments like count to limit substitutions. For example, re.sub('\d', '#', '123 apple street') would replace all digits with '#', resulting in '### apple street'. This function is useful in data cleaning and formatting tasks, such as masking sensitive information or standardizing text .
To extract all numbers from a given string using Python's regular expressions, the re.findall() method can be used with the pattern '\b\d+\b'. This pattern matches one or more digits as a standalone word by ensuring word boundaries with '\b' on either side. re.findall() returns a list of all substrings where the regex finds a match, enabling extraction of each number in the string as individual items in the list .
In Python regular expressions, greedy and non-greedy (or lazy) matching determine how much of the string is captured by the quantifiers. Greedy matching attempts to match as much of the string as possible, exemplified by the '*' and '+' quantifiers, which extend the match to include the largest possible portion of the text. Non-greedy matching, achieved by adding a '?' after a greedy quantifier (e.g., '*?', '+?'), will capture the smallest possible match. This distinction is important when parsing text where the simplest or smallest component is of interest, and longer matches may encompass unintended or additional content .