Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Inconsistent behavior between re.split() and Pattern.split()

The behavior of re.Pattern.split() should be identical to its re.split() counterpart according to its official documentation (v3.10.4 at the time of writing).

Pattern.split(string, maxsplit=0)

Identical to the split() function, using the compiled pattern.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The following example, however, does not seem to agree with that. Only re.Pattern.split() gives the expected result. Did I misread something, or it’s OK to report this issue?

>>> import re
>>> re.split(r"k/a", "a K/A b", re.I)
['a K/A b']
>>> re.compile(r"k/a", re.I).split("a K/A b")
['a ', ' b']

Tested with python 3.10.4 on WSL ubuntu 20.04 LTS (amd64), debian 11 and Windows 11. Official python, python-dotenv and Anaconda python behaved the same.

>Solution :

The signature of re.split is:

re.split(pattern, string, maxsplit=0, flags=0)

So in order to pass any flags, you need to use a keyword argument, otherwise the flags are interpreted as the maxsplit parameter:

>>> re.split(r"k/a", "a K/A b", flags=re.I)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading