This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: re.sub ignores flag re.M
Type: behavior Stage: resolved
Components: IO Versions: Python 3.8
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: jlaurens, mrabarnett
Priority: normal Keywords:

Created on 2020-11-26 13:47 by jlaurens, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (2)
msg381901 - (view) Author: Jérôme Laurens (jlaurens) Date: 2020-11-26 13:47
Test code:
```
import re
test='''012345678
         
012345678
'''
pattern = r'^\s+?$'
m = re.search(pattern, test, re.M)
if m:
    print(f'TEST FOUND "{m.span()}"')

    def replace(m):
        print(f'TEST REMOVE {m.span()}')
        return ''

    test = re.sub(pattern, replace, test, re.M)
    m = re.search(pattern, test, re.M)
    if m:
        print(f'TEST STILL THERE "{m.span()}"')

print('COMPILE PATTERN FIRST')
pattern_re = re.compile(pattern, re.M)
m = re.search(pattern_re, test)
if m:
    print(f'TEST FOUND "{m.span()}"')

    def replace(m):
        print(f'TEST REMOVE {m.span()}')
        return ''

    test = re.sub(pattern_re, replace, test)
    m = re.search(pattern_re, test)
    if m:
        print(f'TEST STILL THERE "{m.span()}"')
```

Actual output:

TEST FOUND "(10, 19)"
TEST STILL THERE "(10, 19)"
COMPILE PATTERN FIRST
TEST FOUND "(10, 19)"
TEST REMOVE (10, 19)

This is an inconsistency between re.search and re.sub. Either this is a bug in the code or in the documentation.
msg381905 - (view) Author: Matthew Barnett (mrabarnett) * (Python triager) Date: 2020-11-26 16:01
Not a bug.

Argument 4 of re.sub is the count:

    sub(pattern, repl, string, count=0, flags=0)

not the flags.
History
Date User Action Args
2022-04-11 14:59:38adminsetgithub: 86639
2020-11-26 16:01:39mrabarnettsetstatus: open -> closed

nosy: + mrabarnett
messages: + msg381905

resolution: not a bug
stage: resolved
2020-11-26 13:47:10jlaurenscreate