简体   繁体   English

从较长的字符串中解析出字符串的最佳方法是什么?

[英]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)我需要解析出“ABCD”(其中 ABCD 每天都会是不同的值)

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值后总会有一个“.p”
  2. There will always be a "test-load-" before the value.值之前总会有一个“test-load-”。

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我想到的事情是以某种方式抓住最后一个“/”之后的所有内容,然后删除最后两个字符(以“.p”为例,然后做一个

 .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.为了增加弹性,将.+替换为字符 class 仅包含该部分中可能出现的字符。

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.一个比使用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.

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