I have a xml duration in the format of "0H0M0.25S", where H, M, S stands for hour, month, second. Now I wish to parse this string and assign it to integer hour, minute, and double second. i.e.
我的xml持续时间格式为“0H0M0.25S”,其中H,M,S代表小时,月,秒。现在我希望解析这个字符串并将其分配给整数小时,分钟和双秒。即
string s="0H0M0.25S";//input
int hour, minute;double second;//variable to assign
is there a way to achieve it using regular expression, which can assign all this variable in one go?
有没有办法使用正则表达式来实现它,它可以一次性分配所有这些变量?
2 个解决方案
#1
2
Try this:
尝试这个:
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);
You might need to compensate for culture while parsing double.
在解析double时,您可能需要补偿文化。
#2
1
Or you can ditch Regex altogether and work with DateTime
:
或者你可以完全抛弃Regex并使用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
}
#1
2
Try this:
尝试这个:
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);
You might need to compensate for culture while parsing double.
在解析double时,您可能需要补偿文化。
#2
1
Or you can ditch Regex altogether and work with DateTime
:
或者你可以完全抛弃Regex并使用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
}