开发者

what is the best way to parse out string from longer string?

i have a string that looks like this:

"/dir/location/test-load-ABCD.p"

and i need to parse out "ABCD" (where ABCD will be a different value every day)

The only things that i know that will always be consistent (to use for the logic for parsing) are:

  1. There will always be be a ".p" after the value
  2. There will always be a "test-load-" before the value.

The things i thought of was somehow grab everything past the last "/" and then remove the last 2 characters (to take case of the ".p" and then to do a

 .Replace("test-load-", "")

but it felt kind of hacky so i wanted开发者_运维百科 to see if people had any suggestions on a more elegant solution.


You can use a regex:

static readonly Regex parser = new Regex(@"/test-load-(.+)\.p");

string part = parser.Match(str).Groups[1].Value;

For added resilience, replace .+ with a character class containing only the characters that can appear in that part.

Bonus:
You probably next want

DateTime date = DateTime.ParseExact(part, "yyyy-MM-dd", CultureInfo.InvariantCulture);


Since this is a file name, use the file name parsing facility offered by the framework:

var fileName = System.IO.Path.GetFileNameWithoutExtension("/dir/location/test-load-ABCD.p");
string result = fileName.Replace("test-load-", "");

A “less hacky” solution than using Replace would be the use of regular expressions to capture the solution but I think this would be overkill in this case.


string input = "/dir/location/test-load-ABCD.p";

Regex.Match(input, @"test-load-([a-zA-Z]+)\.p$").Groups[1].Value
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜