[英]Transform string by regular expression
有没有办法像这样转换字符串
http://blar1.s3.shamazonaws.com/ZZ/bstd-20140801-004000-0500.time.gz
至
C:\Temp\2014\08\
使用单个正则表达式?
有很多文件需要定期下载,我需要将这些文件存储在按年份和月份组织的目录结构中。 它们在名称中都具有相同的日期部分-例如在我的示例中为“ 20140801-004000-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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.