【问题标题】:extracting string with Indexof in c#在 C# 中使用 Indexof 提取字符串
【发布时间】:2012-04-24 21:54:24
【问题描述】:

我正在尝试提取此文件名中的数字部分。 "姓名、姓氏_123456_state_city.pdf"

我已经走到这一步了..

idstring = file.Substring(file.IndexOf("_") + 1, 
    (file.LastIndexOf("_") - file.IndexOf("_") - 1));

【问题讨论】:

  • 数字总是在第一个破折号之后吗?您可以在 _ 上使用 Split 并获取数组的第一个元素

标签: c# indexof


【解决方案1】:

这是正则表达式可能更好的情况之一:

_(\d+)_

而且,这是你将如何使用它

    string input = "Name, lastname_123456_state_city.pdf";
    string regexPattern = @"_(\d+)_";

Match match = Regex.Match(input, regexPattern, RegexOptions.IgnoreCase);

if (match.Success)
    string yourNumber = match.Groups[1].Value;

【讨论】:

    【解决方案2】:
    var firstUnderscore = file.IndexOf("_");
    var nextUnderscore = file.IndexOf("_", firstUnderscore + 1);
    var idstring = file.Substring(firstUnderscore + 1, nextUnderscore - firstUnderscore - 1);
    

    【讨论】:

    • 谢谢,我希望我能选择两个答案!
    【解决方案3】:

    为什么不直接使用正则表达式?测试@"_([0-9]*)_" 应该可以解决问题。

    【讨论】:

      【解决方案4】:

      您可以使用System.Text.RegularExpressions.Regex

      var regex = new Regex(@"^.*_(?<number>\d+)_.*\.pdf");
      var idstring=regex.Match(file).Groups["number"].Value;
      

      【讨论】:

        猜你喜欢
        • 2020-07-06
        • 2016-06-09
        • 2016-06-17
        • 1970-01-01
        • 2016-02-03
        • 1970-01-01
        • 1970-01-01
        • 2015-01-10
        • 2016-02-05
        相关资源
        最近更新 更多