如何解析含西班牙语日期规则的自定义格式字符串
自定义间隔字符串解析:需求、实现与优化方向
格式规则
格式表达式:
"(null|L-D,S,D)C(\d){1,2}(H|D|S|M)"
规则说明:
- 第一组:可为空,或西班牙语星期首字母(
L、M、X、J、V、S、D),或这些字母的逗号分隔列表,或连续星期组(如J-D代表J、V、S、D) C表示“每隔”- 第二组:0-99之间的数字
- 第三组:
H(小时)、D(天)、S(周)或M(月)
解析示例
"C12H"译为“每隔12小时”"LC6S"译为“周一每隔6周”"L,X,VC6H"译为“周一、周三、周五每隔6小时”"L-VC12H"译为“周一至周五每隔12小时”"J-LC12H"暂未解析,可理解为“周四至周一每隔12小时”
现有C#实现代码
static public void InterpretInterval(string Interval) { // Format: (null|L-D,S,D)C(\d{1,2})(H|D|S|M) string pattern1 = @"^(([LMXJVSD][-,]?){0,7})C(\d{1,2})(H|D|S|M)\s*$"; Regex rex = new Regex(pattern1, RegexOptions.Compiled); string msg = ""; Match m = rex.Match(Interval); if (m.Success) { MessageBox.Show(string.Format("Número de grupos: {0}", m.Groups.Count.ToString())); List<string> days = SplitDays(m.Groups[1].Value); string temp = ""; if (m.Groups[4].Value == "H") temp = "Hours"; else if (m.Groups[4].Value == "D") temp = "Days"; else if (m.Groups[4].Value == "S") temp = "Weeks"; else if (m.Groups[4].Value == "M") temp = "Months"; else temp = "Error"; msg = string.Format("Original: {0}\n\rDaysOfWeek: {1}\n\rFrequency: {2} {3}", Interval, string.Join(',', days.ToArray()), m.Groups[3].Value, temp); } else { msg = "Could not parse."; } MessageBox.Show(msg); return; } static List<string> SplitDays(string value) { List<string> temp = new List<string>(); var CommaGroups = value.Split(','); if (CommaGroups[0] == "") { // By the moment just handled this way i.e: "C24H" is more frequent than "C8S" so right now I translate to "all days" every "number" "hours|days|weeks|months" temp.Add("from L to D"); } else { foreach (var group in CommaGroups) { if (group.Length == 1) { temp.Add(group); continue; } var DashGroup = group.Split("-"); if (DashGroup.Length == 2) { temp.Add(string.Format("de {0} a {1}", (string)DashGroup[0], (string)DashGroup[1])); continue; } MessageBox.Show("Days of week parsing error."); return new List<string>(); } } return temp; }
优化需求
- 现有代码存在优化空间
- 需支持多语言解析与输出
- 算法不应依赖当前的字符数量限制
- 欢迎提供其他编程语言的优化实现方案
内容的提问来源于stack exchange,提问作者raululm
相关产品推荐
相关产品推荐

