如何从字符串中提取值,如下所示:Lambertseter_InfoCloseDay_07_09_2014_19_55_52?
格式如下:<Location>_<TypeOfFile>_<DD>_<MM>_<YYYY>_<HH>_<MM>_<SS>
我试过了:
string Mystring = "Lambertseter_InfoCloseDay_07_09_2014_19_55_52";
string[] splittedFileString = Mystring.Split('_');
string[] formatArray = { "Bingohall: ", "Filetype: ", "Day: ", "Month: ", "Year: ", "Hour: ", "Minute: ", "Second: " };
for (int i = 0; i < formatArray.Length; i++)
{
formatArray[i] += splittedFileString[i];
}
这似乎至少起作用,但我是以正确的方式做到这一点吗?是否有一种更简单的方法来管理字符串?
答案 0 :(得分:0)
如果您的数据是常规数据,则此正则表达式将起作用:
var regex = new Regex(@"(?<Location>\w+)_(?<TypeOfFile>\w+)_(?<DD>\d+)_(?<MM>\d+)_(?<YYYY>\d+)_(?<HH>\d+)_(?<MIN>\d+)_(?<SS>\d+)", RegexOptions.ExplicitCapture);
var match = regex.Match("Lambertseter_InfoCloseDay_07_09_2014_19_55_52");
var groups = match.Groups;
var output = $"Bingohall: {groups["Location"].Value}, Filetype: {groups["TypeOfFile"].Value}, Day: {groups["DD"].Value}, Month: {groups["MM"].Value}, Year: {groups["YYYY"].Value}, Hour: {groups["HH"].Value}, Minute: {groups["MIN"].Value}, Second: {groups["SS"].Value}";