c# - 日期格式的正则表达式
问题描述
我需要将在以下格式中找到/匹配的正则表达式
2018 年 7 月 1 日、2018 年 7 月 2 日、2018 年 3 月 4 日 (带逗号和不带逗号的 dd/mmm/yyyy 和 mm/dd/yyyy)我有以下正则表达式,在这里工作正常
正则表达式是
(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*?\s+\d{1,2}(?:[a-z]{2})?(?:\s+|,\s*)\d{4}\b
但它不适用于我的代码,我不知道我放错了什么......
我的代码是
Regex regex = new Regex(@"(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*?\s+\d{1,2}(?:[a-z]2})?(?:\s+|,\s*)\d{4}\b");
Match match = regex.Match(html);
return match.Value;
上面的表达式也负责
2020 年 1 月 1 日,但我还需要2020 年 1 月 1 日..
解决方案
这是 C# 函数,它为您提到的所有格式匹配并返回结果 true 或 false,您也可以在格式数组中添加更多日期格式
public bool checkIsValidDateTime(string date)
{
var formats = new[] { "dd MMMM yyyy", "MMMM dd yyyy", "dd MMMM ,yyyy", "MMMM dd, yyyy", "d MMMM yyyy", "MMMM d yyyy", "d MMMM ,yyyy", "MMMM d, yyyy" };
DateTime dt;
var replacements = new[]{
new{Find="st",Replace=""},
new{Find="nd",Replace=""},
new{Find="rd",Replace=""},
new{Find="th",Replace=""}
};
foreach (var set in replacements)
{
date = date.Replace(set.Find, set.Replace);
}
bool isValid = DateTime.TryParseExact(date, formats, null, DateTimeStyles.None, out dt);
return isValid;
}
// which return true for following formats
string input = "1st July 2018";
string input2 = "July 2nd 2018";
string input3 = "3rd March ,2018";
string input4 = "January 4th, 2020";
string input5 = "20th January 2020";
bool isvalid1 = checkIsValidDateTime(input); // result true
bool isvalid2 = checkIsValidDateTime(input2); // result true
bool isvalid3 = checkIsValidDateTime(input3); // result true
bool isvalid4 = checkIsValidDateTime(input4); // result true
bool isvalid5 = checkIsValidDateTime(input5); // result true
推荐阅读
- python - 这些 pandas 的 group by 语句是做什么的?
- sql-server - 使用条件计算创建函数
- facebook - 来自“user_link”权限的 url 获取错误
- java - -+1 字符串正则表达式检查字符串编号是否同时包含两个符号 java
- ibm-midrange - RPGLE 程序中的记录选择
- python - 使用 scipy 最小化带有参数的函数
- python - 如何使用 f"" 字符串而不是 .format() 打印二进制数?
- java - spring boot 提供嵌套在模板文件夹中的 html 文件
- python - 为什么会出现错误 AttributeError:“WebDriver”对象没有属性“executes_script”
- elasticsearch - 如何将此 elasticsearch 查询从 2.x 转换为 5.x 索引?