Support tickets, notes and descriptions hold useful values inside free text. A regular expression describes the pattern; .str methods apply it to a column:
tickets["subject"].str.extract(r"#(\d+)", expand=False)
\d is a digit, \w a letter, digit or underscore, \s a space; + means "one or more".
- Parentheses mark the part to keep:
str.extract returns what the first group matched (NaN when nothing matches). expand=False returns a Series instead of a one-column table.
str.contains(pattern, case=False) tests for a match; str.replace(pattern, "", regex=True) removes one; str.findall returns every match.
- Special characters
. [ ] ( ) $ + ? * mean something in a pattern. To match them literally, put a backslash in front: \[urgent\] or \$.
- Write patterns as raw strings,
r"...", so Python leaves the backslashes alone.
Check a pattern on the rows it should not match too: patterns tend to match more than you expect.