如何在python中使用正则表达式

2024-04-27 21:12:53 发布

您现在位置:Python中文网/ 问答频道 /正文

抱歉,这似乎是一个重复的问题,但我真的需要帮助

所以我有一个文本文件,它有一行的形式:

Thu Apr 28 20:51:37 +0000 2011 :: Melanie Caldwell :: judeyqwaller :: Hong Kong :: P000352670 - Toshiba Satellite 5205 Series TouchPad: Toshiba Satellite 5205 Series TouchPad - P000352670COMPATIB... http://t.co/QU5jA6U5

我只需要拉出行中在:: Hong Kong::之后开始的部分,即。 P000352670...,依此类推。你知道吗

如何使用正则表达式执行此操作?你知道吗


Tags: apr形式serieshong文本文件touchpadkongsatellite
3条回答

您不需要正则表达式,因为它非常简单,您可以执行以下操作:

x = string.split("::")[-1]

如果字符串是您的文本行

编辑新问题(假设您使用的是python 2.5+):

string = "682698_62876_26861"
print string.rpartition('_')[0]

这将输出您所需要的:

682698_62876
>>> row = "Thu Apr 28 20:51:37 +0000 2011 :: Melanie Caldwell :: judeyqwaller :: Hong Kong :: P000352670 - Toshiba Satellite 5205 Series TouchPad: Toshiba Satellite 5205 Series TouchPad - P000352670COMPATIB... http://t.co/QU5jA6U5"
>>> row.rpartition('::')[2]
' P000352670 - Toshiba Satellite 5205 Series TouchPad: Toshiba Satellite 5205 Series TouchPad - P000352670COMPATIB... http://t.co/QU5jA6U5'

试试这个:

res = ' :: '.join(row.split(' :: ')[4:])

相关问题 更多 >