繁体   English   中英

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

[英]Comma-separated time regex c#?

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

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

我是正则表达式的新手,所以在学习了快速启动正则表达式教程之后 ,我写了这样的:

(([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

谁能帮助我让这个正则表达式按预期工作?

您可以在不使用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,
\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";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM