检查字符串中是否存在日期,如果存在,请将其删除

时间:2014-06-25 11:38:59

标签: python regex

如何检查字符串是否包含YYYY-MM-DD格式的日期,若是,请将其删除?

text = '2014-06-25 Testing 12345'
text = removeDate(text)
print(text)

>> 'Testing 12345'

5 个答案:

答案 0 :(得分:4)

通过使用正则表达式,假设日期格式始终为YYYY-MM-DD

import re

text = '2014-06-25 Testing 12345'
text = re.sub('\d{4}-\d{2}-\d{2}', '', text).strip()
print (text)

答案 1 :(得分:1)

怎么样

import re
def removeDate( text ):
    return re.sub( '\d\d\d\d-\d\d-\d\d ?', '', text )

这将删除任何4位数,短划线,2位数字,短划线,2位数和#34;"的可选空格序列。

答案 2 :(得分:1)

您可以使用正则表达式进行检查;

re.match('(\d{4})[/.-](\d{2})[/.-](\d{2})$', text)

答案 3 :(得分:0)

您可以使用日期格式http://www.regular-expressions.info/dates.html的正则表达式,一旦找到字符串的字符串/部分,就可以在python中替换它http://www.tutorialspoint.com/python/string_replace.htm

答案 4 :(得分:0)

如果您的字符串包含日期为YYYY-MM-DD或YYYY.MM.DD,则会将其取出并为您提供剩余的字符。

import re
def date_elimination(text):
    date_pattern = re.search("(\d{4}[-.]+\d{2}[-.]+\d{2})", text)
    if date_pattern is not None and date_pattern != 'None':
        text = re.sub('(\d{4}[-.]+\d{2}[-.]+\d{2})', '', text)
        return text.strip()
    else:
        return text.strip()
test = "2014-06-25 Testing 12345"
print date_elimination(test)
相关问题