i am struggling with regex in Python, i would like to find the position of the last token in a String.
Example: "mydrive/projects/test/version01"
Now i would like to get the position of the symbol between "test" and "version01"
import re
txt = "mydrive/projects/test/version01"
p = re.compile("/^.*/(.*)$/")
m = re.search(p, txt)
m.group(0)
#but m.group(0) delivers None
but with this i am getting "None" i tried several things, but couldn't get it find the pattern. By the way i got this regex from a javascript page, but i think the patterns are the same.
thank you very much!
You're using the re
module in the wrong way.
You have 2 errors:
search.sub
's documentation . re
doesn't need the slashes around the regexp. Either use:
p = re.compile("^.*/(.*)$")
m = p.search(txt)
m.group(0)
Or:
m = re.search("^.*/(.*)$", txt)
m.group(0)
You say: Now i would like to get the position of the symbol between "test" and "version01".
I don't see how the regex is going to help you much. You could try the following:
Reverse scan for the symbol, if you know what the symbol is (I am assuming you do, since it is in the regex too):
>>> txt = "mydrive/projects/test/version01"
>>> txt.rfind('/')
21
If you don't know the separator:
>>> import os.path
>>> len(os.path.dirname(txt))
21
I'm curious whether you're wanting to use re
or are actually trying to split that filepath ?
os.path
has all you need if that's the case, if not forgive me for answering a non asked question.
In [212]: import os
In [213]: os.path.split("mydrive/projects/test/version01")
Out[213]: ('mydrive/projects/test', 'version01')
If you're trying to find the position of the symbol bewteen "test" and "version01" I'd just use rfind :
txt = "mydrive/projects/test/version01"
print txt.rfind("/");
which prints out 21
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.