[New-bugs-announce] [issue42473] re.sub ignores flag re.M

Jérôme Laurens report at bugs.python.org
Thu Nov 26 08:47:10 EST 2020


New submission from Jérôme Laurens <jerome.laurens at u-bourgogne.fr>:

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.

----------
components: IO
messages: 381901
nosy: jlaurens
priority: normal
severity: normal
status: open
title: re.sub ignores flag re.M
type: behavior
versions: Python 3.8

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue42473>
_______________________________________


More information about the New-bugs-announce mailing list