如何使用正则表达式删除子字符串的结尾?

2024-05-08 19:03:48 发布

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

我将Occur_DateOccur_Time列(都由字符串组成)组合成一个字符串列Occur_Date_Time。我试图使用正则表达式r':[0-9]{2}$'从新列中的时间中删除秒,这表示只删除以冒号开头,后跟以字符串结尾的两个数字的子字符串。已使用strip函数删除了这些数据,但也删除了比预期更多的数据(例如索引位置2行中的月份)。我已附上我的代码以供审查。有人能在这件事上给我指点方向吗

Referenced Code


1条回答
网友
1楼 · 发布于 2024-05-08 19:03:48

对某个数字进行正向查找将有助于:

f'(?<=\d):\d{2}$'
Positive Lookbehind (?<=\d)
Assert that the Regex below matches
\d matches a digit (equivalent to [0-9])
: matches the character : literally (case sensitive)
\d matches a digit (equivalent to [0-9])
{2} matches the previous token exactly 2 times
$ asserts position at the end of a line

相关问题 更多 >