鉴于时间戳可以有多种结构,即
- 时:分:秒
- 时:分:秒
- MMM:SS
- MM:SS
- 男:SS
目前我正在使用 re.findall()
和 |
替代运算符。
有没有更有效的方法来查找所有上述可能类型的时间戳 在字符串中而不是以下内容:
aString = "the cat (01:03) sat on [01:01:01] the ( 9:13 )mat( 1:10:11)."
bString = "the cat 01:14:23.447 sat on the mat"
cString = "the cat 01:14:23.447 --> 01:17:10.239 sat on the mat"
dString = "the cat 323:14 sat on the mat"
v = re.findall('\d{2}:\d{2}:\d{2}|\d:\d{2}:\d{2}|\d{3}:\d{2}|\d{2}:\d{2}|\d:\d{2}',aString)
x = re.findall('\d{2}:\d{2}:\d{2}|\d:\d{2}:\d{2}|\d{3}:\d{2}|\d{2}:\d{2}|\d:\d{2}',bString)
y = re.findall('\d{2}:\d{2}:\d{2}|\d:\d{2}:\d{2}|\d{3}:\d{2}|\d{2}:\d{2}|\d:\d{2}',cString)
z = re.findall('\d{2}:\d{2}:\d{2}|\d:\d{2}:\d{2}|\d{3}:\d{2}|\d{2}:\d{2}|\d:\d{2}',dString)
v
['01:03', '01:01:01', '9:13', '1:10:11']
x
['01:14:23']
y
['01:14:23', '01:17:10']
z
['323:14']
注意:我不关心毫秒是否包含在时间戳中。
最佳答案
你可以使用这个:
aString = "the cat (01:03) sat on [01:01:01] the ( 9:13 )mat( 1:10:11)."
bString = "the cat 01:14:23.447 sat on the mat"
cString = "the cat 01:14:23.447 --> 01:17:10.239 sat on the mat"
dString = "the cat 323:14 sat on the mat"
v = re.findall('\d{1,3}(?::\d{2}){1,2}', aString)
x = re.findall('\d{1,3}(?::\d{2}){1,2}', bString)
y = re.findall('\d{1,3}(?::\d{2}){1,2}', cString)
z = re.findall('\d{1,3}(?::\d{2}){1,2}', dString)
print(v, x, y, z, sep='\n')
输出:
['01:03', '01:01:01', '9:13', '1:10:11']
['01:14:23']
['01:14:23', '01:17:10']
['323:14']
说明:
-
\d{1,3}
匹配至少 1 个、最多 3 个数字 -
(?:
启动非捕获组-
:\d{2}
匹配冒号和 2 位数字
-
-
)
端基 -
{1,2}
与前面的组匹配至少 1 次,最多 2 次li>
关于python - 查找字符串中所有出现的可变时间戳结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49609262/