[英]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.