简体   繁体   English

RegEx-查找字符串中最后找到的符号的位置

[英]RegEx - Find Position of last found symbol in String

i am struggling with regex in Python, i would like to find the position of the last token in a String. 我在Python中使用正则表达式时遇到了麻烦,我想在字符串中找到最后一个标记的位置。

Example: "mydrive/projects/test/version01" 示例:“ mydrive / projects / test / version01”

Now i would like to get the position of the symbol between "test" and "version01" 现在我想获取符号在“ test”和“ 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. 顺便说一下,我从一个javascript页面得到了这个正则表达式,但是我认为模式是相同的。

thank you very much! 非常感谢你!

You're using the re module in the wrong way. 您使用错误的方式使用了re模块。

You have 2 errors: 您有2个错误:

  1. You try to use a compiled regexp object as if it were a pattern Actually this is perfectly fine, see search.sub 's documentation . 您尝试使用已编译的regexp对象,就像它是一种模式一样。实际上,这很好,请参阅search.sub的文档
  2. Python's re doesn't need the slashes around the regexp. Python的re不需要正则表达式的斜线。

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". 您说:现在,我想获取符号在“ test”和“ 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 ? 我很好奇您是要使用re还是实际上是在尝试拆分该文件路径?

os.path has all you need if that's the case, if not forgive me for answering a non asked question. 如果是这样, os.path拥有您所需要的一切,如果不能原谅我回答一个未问的问题。

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 : 如果您想在“ test”和“ version01”之间找到符号的位置,我将只使用rfind

txt = "mydrive/projects/test/version01"
print txt.rfind("/");

which prints out 21 . 打印出21

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM