1

我有一些看起来像这样的字符串

S25m\S25m_16Q_-2dB.png
S25m\S25m_1_16Q_0dB.png
S25m\S25m_2_16Q_2dB.png

我想获取斜杠和最后一个下划线之间的字符串,以及最后一个下划线和扩展名之间的字符串,所以

期望:

[S25m_16Q, S25m_1_16Q, S25m_2_16Q]
[-2dB, 0dB, 2dB]

我能够通过做得到斜线和扩展之间的全部内容

foo = "S25m\S25m_16Q_-2dB.png"
match = re.search(r'([a-zA-Z0-9_-]*)\.(\w+)', foo)
match.group(1)

但我不知道如何制作一个模式,所以我可以用最后一个下划线分割它。

4

3 回答 3

5

捕获您想要获取的组。

>>> re.search(r'([-\w]*)_([-\w]+)\.\w+', "S25m\S25m_16Q_-2dB.png").groups()
('S25m_16Q', '-2dB')
>>> re.search(r'([-\w]*)_([-\w]+)\.\w+', "S25m\S25m_1_16Q_0dB.png").groups()
('S25m_1_16Q', '0dB')
>>> re.search(r'([-\w]*)_([-\w]+)\.\w+', "S25m\S25m_2_16Q_2dB.png").groups()
('S25m_2_16Q', '2dB')

*贪婪地匹配前一个字符集(尽可能多地消耗);它一直持续到最后,_因为\w它包含字母、数字和下划线。


>>> zip(*[m.groups() for m in re.finditer(r'([-\w]*)_([-\w]+)\.\w+', r'''
... S25m\S25m_16Q_-2dB.png 
... S25m\S25m_1_16Q_0dB.png
... S25m\S25m_2_16Q_2dB.png
... ''')])
[('S25m_16Q', 'S25m_1_16Q', 'S25m_2_16Q'), ('-2dB', '0dB', '2dB')]
于 2013-08-21T07:15:46.590 回答
0

A non-regex solution (albeit rather messy):

>>> import os
>>> s = "S25m\S25m_16Q_-2dB.png"
>>> first, _, last = s.partition("\\")[2].rpartition('_')
>>> print (first, os.path.splitext(last)[0])
('S25m_16Q', '-2dB')
于 2013-08-21T07:17:12.183 回答
-3

我知道它说 using re,但为什么不直接使用split呢?

strings = """S25m\S25m_16Q_-2dB.png
S25m\S25m_1_16Q_0dB.png
S25m\S25m_2_16Q_2dB.png"""

strings = strings.split("\n")

parts = []
for string in strings:
    string = string.split(".png")[0] #Get rid of file extension
    string = string.split("\\")
    splitString = string[1].split("_")
    firstPart = "_".join(splitString[:-1]) # string between slash and last underscore
    parts.append([firstPart, splitString[-1]])


for line in parts:
    print line
['S25m_16Q', '-2dB']
['S25m_1_16Q', '0dB']
['S25m_2_16Q', '2dB']

然后只需转置数组,

for line in zip(*parts):
    print line
('S25m_16Q', 'S25m_1_16Q', 'S25m_2_16Q')
('-2dB', '0dB', '2dB')
于 2013-08-21T07:22:37.320 回答