[英]How to write this Regex expression?
所以我在输入中有一个字符串表示持续时间的格式。 这种格式可以是各种类型,如:“hh:mm:ss”或“sssss”或“”hhmmss“等......
我的目标是了解用户插入的此字符串是否为有效格式。 我到现在为止做了什么:
Regex rgx = new Regex("[^a-zA-Z0-9 ]");
input = rgx.Replace(input, string.Empty);
在这一点上,我有一个字符串应该采用这种格式“hhmmss”或“sssss”或“mmss”。 我需要检查用户是否错误地插入了一些拼写错误,使用此有效块列表执行Regex.Match
List<string> entry = new List<string> {
"h", "hh", "hhh", "hhhh",
"m", "mm", "mmm", "mmmm", "mmmmm",
"s", "ss", "sss", "ssss", "sssss" };
我怎样才能做到这一点?
编辑:我会尝试解释一些问题。 首先,在我的工具的这个阶段,我只需要检查用户的输入是否有效。 有效,我的意思是,用户将输入的任何格式(使用分隔符或不分隔符),它至少由第二个块组成。 我认为用户不会做任何像input = hsssmhhmms
这样的事情,因为它没有任何意义。 我承认的唯一一件事就是拼写错误(例如按“g”而不是“h”)。 当然问题仍然很难,因为这些数据块可以包含在多个表格中。 这就是为什么我做了第一步,在紧凑的块上工作。
为什么不尝试格式化 ? 如果系统可以格式化,那么userFormat
是一种正确的格式:
private static bool IsValidFormat(string userFormat) {
// Gini pig
TimeSpan sample = new TimeSpan(1234567);
string escaped = string.Concat(userFormat
.Select(c => char.IsLetter(c) || c == '%'
? c.ToString()
: "\\" + c.ToString())); // delimiters like :,;+... should be escaped
try {
sample.ToString(escaped);
return true;
}
catch (FormatException) {
return false;
}
}
...
// is this allowed? - true
Console.WriteLine(IsValidFormat(@"hh;mm;;ss+++ffff*h"));
// is this allowed? - false
Console.WriteLine(IsValidFormat(@"zzzz"));
你能确定订购吗? (h-> m-> s)然后它是:
var match = Regex.Match(input, "^([h]{0,4})[:]?([m]{0,5})[:]?([s]{0,5})$");
if (match.Success)
{
string hours = match.Groups[1].Value;
string mins = match.Groups[2].Value;
string secs = match.Groups[3].Value;
}
如果不:
var match = Regex.Match(tbName.Text, "^([h]{0,4}|[m]{0,5}|[s]{0,5})[:]?([h]{0,4}|[m]{0,5}|[s]{0,5})[:]?([h]{0,4}|[m]{0,5}|[s]{0,5})$");
if (match.Success)
{
string hours = match.Groups.Cast<Group>().Skip(1).Select(x => x.Value).FirstOrDefault(x => x.Contains('h'));
string mins = match.Groups.Cast<Group>().Skip(1).Select(x => x.Value).FirstOrDefault(x => x.Contains('m'));
string secs = match.Groups.Cast<Group>().Skip(1).Select(x => x.Value).FirstOrDefault(x => x.Contains('s'));
}
PS:
如果你替换:
用\\W_
它将允许其他非单词字符(,; -_?等)
?
代表零或一。 - >中间只能有一个。
*
允许零个或多个非单词字符。 - >所以你可以得到类似的东西: "hhh_-_--,.,;;mm,ssss"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.