4

我有以下字符串

"1206292WS_R0_ws.shp"

我正在尝试 re.sub 除了第二个“_”和“.shp”之间的所有内容

在这种情况下,输出将是“ws”。

我已经设法删除了 .shp 但我一生无法弄清楚如何摆脱“_”之前的所有内容

epass = "1206292WS_R0_ws.shp"

regex = re.compile(r"(\.shp$)")

x = re.sub(regex, "", epass)

输出

1206292WS_R0_ws

期望的输出:

ws
4

5 回答 5

7

你真的不需要正则表达式

print epass.split("_")[-1].split(".")[0]


>>> timeit.timeit("epass.split(\"_\")[-1].split(\".\")[0]",setup="from __main__
import epass")
0.57268652953933608

>>> timeit.timeit("regex.findall(epass)",setup="from __main__ import epass,regex
0.59134766185007948

两者的速度似乎非常相似,但拆分速度稍快一些

实际上到目前为止最快的方法

print epass.rsplit("_",1)[-1].split(".")[0]

在 100k 长的字符串上(在我的系统上)需要 3 秒,而其他任何一种方法都需要 35+ 秒

如果您实际上是指第二个_而不是最后一个_,那么您可以这样做

epass.split("_",2)[-1].split(".")  

虽然取决于第二个 _ 是正则表达式的位置,但可能同样快或更快

于 2013-06-05T15:55:33.663 回答
2

你描述的正则表达式是 ^[^_]*_[^_]*_(.*)[.]shp$

>>> import re
>>> s="1206292WS_R0_ws.shp"
>>> regex=re.compile(r"^[^_]*_[^_]*_(.*)[.]shp$")
>>> x=re.sub(regex,r"\1",s)
>>> print x
ws

注意:这是您描述的正则表达式,不一定是解决实际问题的最佳方法。

除了第二个“_”和“.shp”之间的所有内容

正则解释:

^       # Start of the string
[^_]*   # Any string of characters not containing _
_       # Literal 
[^_]*   # Any string of characters not containing _
(       # Start capture group
.*      # Anything
)       # Close capture group
[.]shp  # Literal .shp
$       # End of string    
于 2013-06-05T15:56:07.233 回答
1

此外,如果您不想要正则表达式,您可以使用 rfind 和 find 方法

epass[epass.rfind('_')+1:epass.find('.')]
于 2013-06-05T16:04:55.190 回答
0

也许_([^_]+)\.shp$会做这项工作?

于 2013-06-05T15:54:48.257 回答
0

带 RE 的简单版本

   import re
    re_f=re.compile('^.*_')
    re_b=re.compile('\..*')
    inp = "1206292WS_R0_ws.shp"
    out = re_f.sub('',inp)
    out = re_b.sub('',out)
    print out
    ws
于 2013-06-05T16:24:26.497 回答