首页 > 解决方案 > 从特定位置从 C# 中的字符串中提取值

问题描述

我在一个文件夹中有一堆文件,我正在循环浏览它们。如何从以下示例中提取值?我只需要值0519

DOC 75-20-0519-1.PDF

下面的代码给出了完整的部分包括 -1

Convert.ToInt32(Path.GetFileNameWithoutExtension(objFile).Split('-')[2]);

感谢任何帮助。

标签: c#string

解决方案


您可以尝试正则表达式匹配该值。

图案:

 [0-9]+            - one ore more digits
 (?=[^0-9][0-9]+$) - followed by not a digit and one or more digits and end of string

代码:

  using System.Text.RegularExpressions;

  ...

  string file = "DOC 75-20-0519-1.PDF";

  // "0519"
  string result = Regex
    .Match(Path.GetFileNameWithoutExtension(file), @"[0-9]+(?=[^0-9][0-9]+$)")
    .Value;

如果Split('-') 失败,并且结果是整个字符串,那么您似乎有一个错误的 delimiter。例如,它可以是破折号之一:

  "DOC 75–20–0519–1.PDF";  // n-dash
  "DOC 75—20—0519—1.PDF";  // m-dash

推荐阅读