簡體   English   中英

如何從正則表達式中提取字符串並將其轉換為時間跨度?

[英]how to extract string from regular expression and convert it to timespan?

我正在嘗試從正則表達式中提取字符串,並將其轉換為字符串,然后再次將其轉換為Timespan。

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;
            }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM