如何在python的最后一个句号之后以及包括最后一个句号的字符删除

时间:2019-04-05 12:47:53

标签: python regex

我需要使用正则表达式替换点(包括点)之后的所有内容。

这是我的字符串:

file.exe.abc.dux

我需要使用正则表达式以使最终结果为:

file.exe.abc 

我目前在2行中运行代码: [^\\.]+$后跟\.$以达到上述结果。

我想知道是否有单个正则表达式模式来实现上述结果。

1 个答案:

答案 0 :(得分:0)

使用regex

import re
print(re.findall(r'^.*(?=\.)', s))        # ['file.exe.abc']
print(re.search(r'^.*(?=\.)', s)[0])      # file.exe.abc

使用rsplit()

s = 'file.exe.abc.dux'

print(s.rsplit('.', 1)[0])                 # file.exe.abc

使用rindex()

print(s[:s.rindex(".")])                   # file.exe.abc