2012-07-12 35 views
0

我有一個格式爲「0H0M0.25S」的xml持續時間,其中H,M,S代表小時,月,秒。 現在我想解析這個字符串,並將其賦值爲整數小時,分鐘和雙精度。 即使用正則表達式分配多個變量

string s="0H0M0.25S";//input 
int hour, minute;double second;//variable to assign 

有沒有辦法使用正則表達式來實現它,它可以在一個去分配所有這個變量?

+1

說不定你指的'小時,分鐘,秒',而不是'小時,月,秒':) – 2012-07-12 17:03:31

回答

2

試試這個:

var result = Regex.Match(s, @"(\d*)H(\d*)M(\d*.\d*)"); 
hour = int.Parse(result.Groups[1].Value); 
minute = int.Parse(result.Groups[2].Value); 
second = double.Parse(result.Groups[3].Value); 

可能需要彌補文化在解析雙。

1

或者你可以完全拋棄正則表達式,並與DateTime工作:

string datePattern = @"H\Hm\Ms.ff\S"; 
    var date = new DateTime(); 

    if (DateTime.TryParseExact("0H0M0.25S", datePattern, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out date)) 
    { 
     // Everything you need is in 'date' in just one go :) 
     int hour = date.Hour; 
     int minute = date.Minute; 
     double second = (double)date.Second + ((double)date.Millisecond/1000); 
    } 
    else 
    { 
     // Catch invalid datetime string here 
    }