c# - 从特定位置从 C# 中的字符串中提取值
问题描述
我在一个文件夹中有一堆文件,我正在循环浏览它们。如何从以下示例中提取值?我只需要值0519。
DOC 75-20-0519-1.PDF
下面的代码给出了完整的部分包括 -1。
Convert.ToInt32(Path.GetFileNameWithoutExtension(objFile).Split('-')[2]);
感谢任何帮助。
解决方案
您可以尝试正则表达式以匹配该值。
图案:
[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
推荐阅读
- javascript - TypeScript react - JSX 元素类型“Modal.Header”没有任何构造或调用签名
- python - 如何从神经网络模型输出中解码标准化值?
- powershell - 在 Powershell 5 中更改 PSModulePath
- javascript - 如何在屏幕中间生成不重叠的随机粒子?
- gitlab - 如何通过 API 比较 GitLab 中的两个不同标签?
- python - pymc3:截断正常混合
- android - Unity3D Android Crunch 压缩文件大小混乱
- sql - 我不能做学校作业。需要 SQLite 帮助
- algorithm - 约翰逊算法,其中从源到其他节点的距离不为零
- html - 使用 justify-content: space-evenly 时如何不向左溢出