On Sat, Jan 07, 2023 at 10:48:48AM -0800, Peter Ludemann wrote:
> You can get almost the same result using pattern matching. For example, your
> "foo:bar;baz".partition(":", ";")
> can be done by a well-known matching idiom:
> re.match(r'([^:]*):([^;]*);(.*)', 'foo:bar;baz').groups()

"Well-known" he says :-)

I think that is a perfect example of the ability to use regexes for 
obfuscation. It gets worse if you want to partition on a regex 
metacharacter like '.'

I think that the regex solution is also wrong because it requires you 
to know *exactly* what order the separators are found in the source 
string. If we swap the semi-colon and the colon in the source, but not 
the pattern, the idiom fails:

    >>> re.match(r'([^:]*):([^;]*);(.*)', 'foo;bar:baz').groups()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'NoneType' object has no attribute 'groups'

So that makes it useless for the case where you want to split of any of 
a number of separators, but don't know which order they occur in.

You call it "almost the same result" but it is nothing like the result 
from partition. The separators are lost, and it splits the string all at 
once instead of one split per call. I think this would be a closer 
match:

```
>>> re.split(r'[:;]', 'foo:bar;baz', maxsplit=1)
['foo', 'bar;baz']
```

but even there we lose the information of which separator was 
partitioned on.


-- 
Steve
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/MAKXHSBD2YG3JFGECGAOPOIPZHZU27SW/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to