如何从正则表达式中提取字符串并将其转换为时间跨度?



我正在尝试从正则表达式中提取字符串并将其转换为字符串并再次将其转换为时间跨度。

static Regex myTimePattern = new Regex(@"((d+)+(:d+))$");
static TimeSpan DurationTimespan(string s)
{
if (s == null) throw new ArgumentNullException("s");
Match m = myTimePattern.Match(s);
if (!m.Success) throw new ArgumentOutOfRangeException("s");
string hh = m.Groups[0].Value.PadRight(2, '0');
string mm = m.Groups[2].Value.PadRight(2, '0');
int hours = int.Parse(hh);
int minutes = int.Parse(mm);
if (minutes < 0 || minutes > 59) throw new ArgumentOutOfRangeException("s");
TimeSpan value = new TimeSpan(hours, minutes, 0);
return value;
}

字符串 hh 显示 = "30:00",mm 显示:"30"。我的文本框中收集数据的时间是:"01:30:00"。请帮我找到办法。

如果你的正则表达式看起来像这样:

static Regex myTimePattern = new Regex(@"(d+)+:(d+):d+$");

然后,您可以轻松检索组,如下所示:

string hh = m.Groups[1].Value.PadRight(2, '0');
string mm = m.Groups[2].Value.PadRight(2, '0');

你有理由不使用 HH.mm 格式的解析字符串到 TimeSpan 吗?

您的正则表达式仅涵盖 mm 和 ss。你可以使用这个:

static Regex myTimePattern = new Regex(@"(d{1,2}):(d{1,2}):(d{1,2})");
static TimeSpan DurationTimespan( string s )
{
if ( s == null ) throw new ArgumentNullException("s");
Match m = myTimePattern.Match(s);
if ( ! m.Success ) throw new ArgumentOutOfRangeException("s");
string hh = m.Groups[1].Value;
string mm = m.Groups[2].Value;
int hours   = int.Parse( hh );
int minutes = int.Parse( mm );
if ( minutes < 0 || minutes > 59 ) throw new ArgumentOutOfRangeException("s");
TimeSpan value = new TimeSpan(hours , minutes , 0 );
return value ;
}
static Regex myTimePattern = new Regex(@"^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$");
static TimeSpan DurationTimespan(string s)
{
if (s == null) throw new ArgumentNullException("s");
Match m = myTimePattern.Match(s);
if (!m.Success)
throw new ArgumentOutOfRangeException("s");
DateTime DT = DateTime.Parse(s);
TimeSpan value = new TimeSpan(DT.Hour, DT.Minute, 0);
if (DT.Minute < 0 || DT.Minute > 59)
throw new ArgumentOutOfRangeException("s");
return value;
}

最新更新