如何从不同格式的字符串中获取值 [英] How to get values from strings of different formats

查看:71
本文介绍了如何从不同格式的字符串中获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好。



我有这些字符串,我需要从中提取单独的值。字符串包含年,日,小时,分钟和秒。然而,由于它们为零,因此字符串有时缺少值。有一种简单的方法我仍然可以轻松获得价值吗?



string one =年龄:1y 30d 19h 54m 20s;

string two =年龄:1y 30d 19h 20s;

string three =年龄:30d 19h 54m 20s;

解决方案
是的。使用正则表达式:

  string  inp =  年龄:1y 30d 19h 54m 20s; 
正则表达式timeparts = 正则表达式( @ (小于?年份> \d + y\s *)?(小于?天> \d + d\s *)?(小于?小时> \d + h\s *) ?(小于?闵> \d + m\s *)?(小于?二段> \d + s\s *))?;
匹配m = timeparts.Match(inp);
if (m.Success)
{
Console.WriteLine(m.Groups [ ]);
Console.WriteLine(m.Groups [ Day]);
Console.WriteLine(m.Groups [ Hour]);
Console.WriteLine(m.Groups [ Min]);
Console.WriteLine(m.Groups [ Sec]);
}


只是解析一下。首先确保字符串以'Age:'开头:

  if (str.StartsWith( 年龄:))



然后将其删除

 str = str.Replace( 年龄:  string  .Empty); 



然后将其拆分为部分

  string  [] parts = str.Split(' < span class =code-string>'); 





然后遍历各个部分并查看最后一个字母,以相同的方式将其剥离并使用int.Parse()获取整数值。



然后,我想,你需要将各个部分加在一起。 TimeSpan对此有好处。


Hello.

I have these strings that i need to pull up the seperate values from. The strings contains year,days,hours,minutes and seconds. However the strings are at times missing values due to them being zero. Are there a simple way i can still get the values easy?

string one = "Age: 1y 30d 19h 54m 20s";
string two = "Age: 1y 30d 19h 20s";
string three = "Age: 30d 19h 54m 20s";

解决方案

Yep. Use a Regex:

string inp = "Age: 1y 30d 19h 54m 20s";
Regex timeparts = new Regex(@"(?<Year>\d+y\s*)?(?<Day>\d+d\s*)?(?<Hour>\d+h\s*)?(?<Min>\d+m\s*)?(?<Sec>\d+s\s*)?");
Match m = timeparts.Match(inp);
if (m.Success)
    {
    Console.WriteLine(m.Groups["Year"]);
    Console.WriteLine(m.Groups["Day"]);
    Console.WriteLine(m.Groups["Hour"]);
    Console.WriteLine(m.Groups["Min"]);
    Console.WriteLine(m.Groups["Sec"]);
    }


Just a bit of parsing. First make sure the string starts with 'Age: ':

if (str.StartsWith("Age: "))


then remove it

str = str.Replace("Age: ", string.Empty);


then split it into its parts

string[] parts = str.Split(' ');



then iterate through the parts and look at the last letter, strip this off in the same way and int.Parse() it to get the integer value.

Then, I guess, you need to add the various parts together. A TimeSpan would be good for this.


这篇关于如何从不同格式的字符串中获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆