[英]what is the best way to parse out string from longer string?
我有一個看起來像這樣的字符串:
"/dir/location/test-load-ABCD.p"
我需要解析出“ABCD”(其中 ABCD 每天都會是不同的值)
我知道的唯一會始終保持一致的事情(用於解析邏輯)是:
我想到的事情是以某種方式抓住最后一個“/”之后的所有內容,然后刪除最后兩個字符(以“.p”為例,然后做一個
.Replace("test-load-", "")
但這感覺有點老套,所以我想看看人們是否對更優雅的解決方案有任何建議。
您可以使用正則表達式:
static readonly Regex parser = new Regex(@"/test-load-(.+)\.p");
string part = parser.Match(str).Groups[1].Value;
為了增加彈性,將.+
替換為字符 class 僅包含該部分中可能出現的字符。
獎金:
你可能接下來想要
DateTime date = DateTime.ParseExact(part, "yyyy-MM-dd", CultureInfo.InvariantCulture);
由於這是一個文件名,請使用框架提供的文件名解析工具:
var fileName = System.IO.Path.GetFileNameWithoutExtension("/dir/location/test-load-ABCD.p");
string result = fileName.Replace("test-load-", "");
一個比使用Replace
更“簡單”的解決方案是使用正則表達式來捕獲解決方案,但我認為在這種情況下這將是矯枉過正。
string input = "/dir/location/test-load-ABCD.p";
Regex.Match(input, @"test-load-([a-zA-Z]+)\.p$").Groups[1].Value
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.