通过正则表达式转换字符串
本文关键字:字符串 转换 正则表达式 | 更新日期: 2023-09-27 18:24:32
有没有一种方法可以像一样转换字符串
http://blar1.s3.shamazonaws.com/ZZ/bstd-20140801-004000-0500.time.gz
至
C:'Temp'2014'08'
使用单个正则表达式?
有很多文件需要定期下载,我需要将这些文件存储在按年份和月份组织的目录结构中。它们的名称中都有相同的日期部分,比如我在这里的例子中的"20140801-0400-0500",但链接的其他部分可能不同。
您可以使用以下正则表达式:
^ # start of the string
.+- # match everything until the first hyphen
(?<year>'d{4}) # capture the first four digits into a group named year
(?<month>'d{2}) # capture the next two digits into a group named month
(?<day>'d{2}) # you get the idea...
-.+$ # match everything else until the end of the string
以下剪应该做的工作:
string strRegex = @"^.+-(?<year>'d{4})(?<month>'d{2})(?<day>'d{2})-.+$";
Regex myRegex = new Regex(strRegex, RegexOptions.None);
string strTargetString = @"http://blar1.s3.shamazonaws.com/ZZ/bstd-20140801-004000-0500.time.gz";
string strReplace = @"C:'Temp'${year}'${month}";
return myRegex.Replace(strTargetString, strReplace);