如果输入格式正确,如何使用正则表达式进行比较
How to use Regex to compare if the input is in the right format
我正在尝试比较用户的输入(例如“2020-03-24 13:20:30”)是否具有与“YYYYD-MM-DD H:M:S”相同的格式。
@visualizer.callback([Output("start_time", "valid"), Output("start_time", "invalid")],[Input("start_time", "value")],) def check_validity(text):
pattern = re.compile("**code goes here**")
if (**code goes here**):
is_text = text.endswith(template_date)
return is_text, not is_text
return False, False
仅检查字符串是否与您编写的日期时间格式完全匹配,而不检查日期是否实际存在,此正则表达式解决了您的问题:
>>> import re
>>> simple_datetime_re = re.compile(r"^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d$")
>>> bool(simple_datetime_re.match("2020-03-24 13:20:30"))
True
>>> bool(simple_datetime_re.match("2020-03-24 75:20:81")) # Doesn't make sense from a practical perspective but is matched
True
>>> bool(simple_datetime_re.match("2020-03-24-13:20:30"))
False
此实现使用更少的代码
import re
# Create pattern
date_form = re.compile('^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$')
# Replace with the date string
return bool(date_form.search('date_format'))
我正在尝试比较用户的输入(例如“2020-03-24 13:20:30”)是否具有与“YYYYD-MM-DD H:M:S”相同的格式。
@visualizer.callback([Output("start_time", "valid"), Output("start_time", "invalid")],[Input("start_time", "value")],) def check_validity(text):
pattern = re.compile("**code goes here**")
if (**code goes here**):
is_text = text.endswith(template_date)
return is_text, not is_text
return False, False
仅检查字符串是否与您编写的日期时间格式完全匹配,而不检查日期是否实际存在,此正则表达式解决了您的问题:
>>> import re
>>> simple_datetime_re = re.compile(r"^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d$")
>>> bool(simple_datetime_re.match("2020-03-24 13:20:30"))
True
>>> bool(simple_datetime_re.match("2020-03-24 75:20:81")) # Doesn't make sense from a practical perspective but is matched
True
>>> bool(simple_datetime_re.match("2020-03-24-13:20:30"))
False
此实现使用更少的代码
import re
# Create pattern
date_form = re.compile('^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$')
# Replace with the date string
return bool(date_form.search('date_format'))