{"id":7679,"date":"2021-02-10T09:25:47","date_gmt":"2021-02-10T03:55:47","guid":{"rendered":"https:\/\/pynative.com\/?p=7679"},"modified":"2021-04-13T17:31:59","modified_gmt":"2021-04-13T12:01:59","slug":"python-regex-flags","status":"publish","type":"post","link":"https:\/\/pynative.com\/python-regex-flags\/","title":{"rendered":"Python Regex Flags"},"content":{"rendered":"\n

Python regex allows optional flags to specify when using regular expression patterns with match()<\/a><\/code>, search()<\/a><\/code>, and split()<\/a><\/code>, among others.<\/p>\n\n\n\n

All RE module methods accept an optional flags argument that enables various unique features and syntax variations.<\/p>\n\n\n\n

For example, you want to search a word inside a string using regex. You can enhance this regex’s capability by adding the RE.I<\/code><\/strong> flag as an argument to the search method to enable case-insensitive searching.<\/p>\n\n\n\n

You will learn how to use all regex flags available in Python with short and clear examples.<\/p>\n\n\n\n

First, refer to the below table for available regex flags<\/strong>.<\/p>\n\n\n\n

Flag<\/th>long syntax<\/strong><\/th>Meaning<\/strong><\/th><\/tr><\/thead>
re.A<\/code><\/td>re.ASCII<\/code><\/td>Perform ASCII-only matching instead of full Unicode matching<\/td><\/tr>
re.I<\/code><\/td>re.IGNORECASE<\/code><\/td>Perform case-insensitive matching<\/td><\/tr>
re.M<\/code><\/td>re.MULTILINE<\/code><\/td>This flag is used with metacharacter ^<\/code> (caret) and $<\/code> (dollar).
When this flag is specified, the metacharacter ^<\/code> matches the pattern at beginning of the string and each newline\u2019s beginning (\\n<\/code>).
And the metacharacter $<\/code> matches pattern at the end of the string and the end of each new line (\\n<\/code>)<\/td><\/tr>
re.S<\/code><\/td>re.DOTALL<\/code><\/td>Make the DOT (.<\/code>) special character match any character at all, including a newline. Without this flag, DOT(.<\/code>) will match anything except a newline<\/td><\/tr>
re.X<\/code><\/td>re.VERBOSE<\/code><\/td>Allow comment in the regex. This flag is useful to make regex more readable by allowing comments in the regex.<\/td><\/tr>
re.L<\/code><\/td>re.LOCALE<\/code><\/td>Perform case-insensitive matching dependent on the current locale. Use only with bytes patterns<\/td><\/tr><\/tbody><\/table>
Python regex flags<\/figcaption><\/figure>\n\n\n\n

To specify more than one flag, use the |<\/code> operator to connect them. For example, case insensitive searches in a multiline string<\/p>\n\n\n

re.findall(pattern, string, flags=re.I|re.M|re.X)<\/code><\/span>Code language:<\/span> Python<\/span> (<\/span>python<\/span>)<\/span><\/small><\/pre>\n\n\n

Now let’s see how to use each option flag in Python regex.<\/p>\n\n\n\n

Table of contents<\/h2>