Regular Expressions
Many of these can be found in the Regular Expressions section of Perl Best Practices. In fact, some are directly from the book. If you would like more detail than is provided here, you can find further information in PBP.
- Use the flags 'x' on any regex that is not obvious. The 'x' flag allows whitespace and comments to be used in the regex. These can be used to make a 'difficult' regex readable.
- Use the 'm' and 's' flags. Perl will treat the string as a single long line, but detects multiple lines. '.' matches any character, even "\n" . '^' and '$' , match at the start or end of any line within the string.
- Use '\A' and '\z' in preference to '^' and '$'. The '^' and '$' can change their meaning depending on the flags. '\A' and '\z' always denote the same thing.
- Use '\z' to indicate the end of the string, not '\Z'. '\z' matches the end of the string. '\Z' is basically just another name for '$'.
- Use m{…} in preference to /…/ in multiline regexes.
- Don’t use any delimiters other than /…/ or m{…}.
- Prefer properties to enumerated character classes. '\w' is better than '[A-Za-z0-9_]' because it properly handles non-ascii word characters. YaBB is used world-wide, and we must support these other languages.
- Consider matching arbitrary whitespace, rather than specific whitespace characters.
- Be specific when matching ‘as much as possible’.
- Use capturing parentheses () only when you intend to capture. Otherwise, use grouping parenthesis (?:)
- Use the numeric capture variables only when you’re sure that the preceding match succeeded.
- Always give captured substrings proper names.
- Prefer fixed-string eq comparisons to fixed-pattern regex matches.