以逗号分隔的时间正则表达式#?

时间:2014-04-10 20:23:33

标签: c# regex

我正在尝试为以下模式编写正则表达式

pattern = "Time hh:mm separated by comma + # + Time hh:mm separated by comma";

我是正则表达式的新手,所以在学习Quick start regex tutorial后,我写了这个:

(([0-1][0-9]|[2][0-3]):([0-5][0-9]))+(,+(([0-1][0-9]|[2][0-3]):([0-5][0-9]))
?+,*)*+(#)+(([0-1][0-9]|[2][0-3]):([0-5][0-9]))+(,+(([0-1][0-9]|[2][0-3]):([0-5] 
[0-9]))?+,*)*

这个正则表达式存在一些问题。它匹配一些无效的字符串,如:

 - 02:00,#03:00

 - 02:00#03:00,

有效字符串:

 - 02:00#03:00

 - 02:00,04:00,06:00#03:00

 - 02:00#03:00,06:00

它也没有正确创建群组,我想按以下顺序创建群组:

如果字符串为02:00,04:00,06:00#03:00,则组应为:

 - 02:00
 - 04:00
 - 06:00
 - #
 - 03:00

任何人都可以帮助我让这个正则表达式按预期工作吗?

2 个答案:

答案 0 :(得分:2)

您可以在不使用REGEX的情况下执行此操作:

string str = "02:00,04:00,06:00#03:00";
TimeSpan temp;
bool ifValid = str.Split(new[] { ',', '#' })
                  .All(r => TimeSpan.TryParseExact(r, @"hh\:mm",CultureInfo.InvariantCulture, out temp));

您可以将其解压缩到以下函数:

public bool CheckValid(string str)
{
    TimeSpan temp;
    return str.Split(new[] { ',', '#' })
                      .All(r => TimeSpan.TryParseExact
                                                     (r, 
                                                      @"hh\:mm", 
                                                      CultureInfo.InvariantCulture, 
                                                      out temp));
}

然后检查工作方式:

List<string> validStrings = new List<string>
{
    "02:00#03:00",
    "02:00,04:00,06:00#03:00",
    "02:00#03:00,06:00"
};
Console.WriteLine("VALID Strings");
Console.WriteLine("============================");
foreach (var item in validStrings)
{
    Console.WriteLine("Result: {0}, string: {1}", CheckValid(item), item);
}

Console.WriteLine("INVALID strings");
Console.WriteLine("============================");
List<string> invalidStrings = new List<string>
{
    "02:00,#03:00",
     "02:00#03:00,",
};

foreach (var item in invalidStrings)
{
    Console.WriteLine("Result: {0}, string: {1}", CheckValid(item), item);
}

输出将是:

VALID Strings
============================
Result: True, string: 02:00#03:00
Result: True, string: 02:00,04:00,06:00#03:00
Result: True, string: 02:00#03:00,06:00
INVALID strings
============================
Result: False, string: 02:00,#03:00
Result: False, string: 02:00#03:00,

答案 1 :(得分:0)

\s(([0-1]\d|[2][0-3]):([0-5]\d))((,(([0-1]\d|[2][0-3]):([0-5]\d)))*)#(([0-1]\d|[2][0-3]):([0-5]\d))((,(([0-1]\d|[2][0-3]):([0-5]\d)))*)\s

或者:

String time = "(([0-1]\\d|[2][0-3]):([0-5]\\d))";
String timeSequence = time + "((," + time + ")*)";
String regex = "\\s" + timeSequence + "#" + timeSequence + "\\s";