python - python 获取字符串中某个字符前后的特定子字符串

标签 python regex split

我想将时间与描述字符串分开。 desc 可以有这种类型的字符串:

desc = '08:59 Hudh aes ....' 
desc = '19:59Aksi jeh....' 
desc = 'just letters without time'
desc = '21.19:55Aksi hsue....'
desc = '256.08:59Aksi mane....'

time 包含描述的前 10 个字母 我想找到 : 然后在它之前和之后取两个数字,这样我就可以分割时间

time = ''.join(filter(lambda x: x, desc[0:10].replace(" " , "")))
print  "Time:" , time , time.rsplit(':', 1)[0]

time.rsplit(':', 1)[0] 返回 : 之前的所有数字

time.rsplit(':', 1)[0] 返回 : 之后的所有数字

如何定义在 : 前后仅分割两个数字?这是一个好方法吗?使用正则表达式是更好的主意,我尝试过,但有点复杂?

最佳答案

How to define to split only two numbers after and before :

使用正则表达式;以下正则表达式模式匹配完全 2 位数字,后跟一个冒号,然后完全 两位数字(这正是您所要求的):

import re

desc = '21.19:55Aksi hsue....'
m = re.search(r'(\d{2}):(\d{2})', desc)
if m:
    hour, min = m.groups()
else:
    # no time in desc string
    pass
print 'hour = {}, min = {}'.format(hour, min)

输出

hour = 19, min = 55

关于python - python 获取字符串中某个字符前后的特定子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34199673/

相关文章:

python - 我的 Tetration(复数)函数必须更好地矢量化(Python)

java - 正则表达式 : Find mismatched point (or char index)

string - Lua中如何从字符串中取出1个单词

r - 拆分列 - 但仅当它包含一个或多个特殊字符时

python - 为 Flask 应用程序单元测试设置(模拟)请求 header

python - 重新计算循环内的字符串长度

javascript - 正则表达式删除第一个字符的特殊字符、空格和数字

javascript - string.replace 在 Firefox 中不起作用?

python - 从字符串中的数字中拆分字母

python - 如何使用 Python 从 MacOS 弹出 CD?