简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM