搜索字符串以查找特定格式的值
本文关键字:格式 定格 字符串 查找 搜索 | 更新日期: 2023-09-27 18:21:25
如何从这样的字符串中提取值: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];
}
这似乎至少奏效了,但我这样做对吗?有没有一种更简单的方法可以通过这种方式管理字符串?
如果您的数据是这样的正则表达式,那么这个正则表达式就会起作用:
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}";