python - 查找字符串中所有出现的可变时间戳结构

标签 python regex python-3.x

鉴于时间戳可以有多种结构,即

  • 时:分:秒
  • 时:分:秒
  • 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']

DEMO

说明:

  • \d{1,3}匹配至少 1 个、最多 3 个数字
  • (?:启动非捕获组
    • :\d{2}匹配冒号和 2 位数字
  • )端基
  • {1,2}与前面的组匹配至少 1 次,最多 2 次

关于python - 查找字符串中所有出现的可变时间戳结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49609262/

相关文章:

java - 解析数字地址

python - 在 App Engine 上使用 deferred.defer 时出错

python - Pandas 将所有列的值连接到一个新的列列表中

python - 制作自己的 MNIST 数据集(与 MNIST 格式相同)

Python错误没有那个文件或目录

Mysql REGEXP 用户名

python - 将mp3转换为ogg然后压缩的简单方法? (Python 3)

javascript - 排除文件名的正则表达式

python - 找出要删除的内容

python - 在 Jupyter Notebook 中运行 Python 脚本,并传递参数