import re
match = re.match(‘/:/:/:’,‘/usr/home/:lumberjack’)
match.groups()
(‘usr/home’, ‘’, ‘lumberjack’)
Why is the result not (‘usr’,‘home’,‘lumberjack’)?
import re
match = re.match(‘/:/:/:’,‘/usr/home/:lumberjack’)
match.groups()
(‘usr/home’, ‘’, ‘lumberjack’)
Why is the result not (‘usr’,‘home’,‘lumberjack’)?
In order to preserve formatting, please select any code or traceback that you post and then click the </>
button.
[/:] matches '/'
(.*) wants to match as much as it can, but the later 2 occurences of [/:] require the '/:', so it's forced to match no more than 'usr/home'
[/:] matches '/'
(.*) wants to match as much as it can, but the later occurence of [/:] requires the ':', so it's forced to match ''
[/:] matches ':'
(.*) matches 'lumberjack'
As an aside, from the thread title: if you’re trying to construct a file path, which, on the face of it, is what it looks as if you’re trying to do, there’s a bunch of ready made tools that you can take advantage of, such as, from pathlib
, Path
and PurePath
, to name but two.
Does not result in ('usr', 'home', 'lumberjack')
since the regex does not match the string. The re.match
method only returns matches if the regex matches the whole string. So, I’m guessing you have some copy paste errors there. What are you trying to find out?
It looks wrong because the OP didn’t go through the steps to preserve the formatting.
You can see what was actually posted by looking at the underlying raw form:
When properly formatted, the code looks like this:
import re
match = re.match('[/:](.*)[/:](.*)[/:](.*)','/usr/home/:lumberjack')
match.groups()
('usr/home', '', 'lumberjack')
Thanks - I didn’t realize that!
One of the things I like about https://regex101.com is that it automatically provides this kind of step-by-step explanation of how your pattern works.
How did you get that?
Someone in another post said how to get the raw text.
The URL of this thread is:
https://discuss.python.org/t/why-is-the-output-different-from-what-i-thought/32768
so the URL of the raw text is:
https://discuss.python.org/raw/32768
Useful when a post’s format looks messed up.
Hopefully we won’t need it again until post 65536. (I’m in the app, so didn’t immediately see the normal URL, and the special number threw me off)