【问题标题】:strip out digits or letters at the most right of a string去掉字符串最右边的数字或字母
【发布时间】:2012-01-24 13:09:51
【问题描述】:

我有一个文件名:kjrjh20111103-BATCH2242_20111113-091337.txt

我只需要091337,而不是 txt 或 - 我怎样才能做到这一点。它不必是 6 个数字,它可以或多或少,但总是在“-”之后以及 .“doc”或 .“txt”之前的最后一个数字

【问题讨论】:

  • 使用正则表达式
  • (\d+)\..+$ 这个模式应该适合你
  • @Ramhound,我猜他们知道这一点,因为它被标记为 regex

标签: c# regex c#-4.0


【解决方案1】:

您可以使用正则表达式或简单的字符串操作来执行此操作。对于后者:

int lastDash = text.LastIndexOf('-');
string afterDash = text.Substring(lastDash + 1);
int dot = afterDash.IndexOf('.');
string data = dot == -1 ? afterDash : afterDash.Substring(0, dot);

个人我觉得这比正则表达式更容易理解和验证,但你的里程可能会有所不同。

【讨论】:

  • 我可能会建议独立于从名称字符串中拆分数字来解析文件名 - 仅通过解析文件名就有相当大的娱乐潜力。
【解决方案2】:
String fileName = kjrjh20111103-BATCH2242_20111113-091337.txt;
String[] splitString = fileName.Split ( new char[] { '-', '.' } );
String Number = splitString[2];

【讨论】:

  • 数字应该是一个字符串,否则他们的例子091337会被解析为91337
【解决方案3】:

正则表达式:.*-(?<num>[0-9]*). 应该可以完成这项工作。 num capture group 包含你的字符串。

【讨论】:

    【解决方案4】:

    正则表达式是:

    string fileName = "kjrjh20111103-BATCH2242_20111113-091337.txt";
    string fileMatch = Regex.Match(fileName, "(?<=-)\d+", RegexOptions.IgnoreCase).Value;
    

    【讨论】:

      【解决方案5】:
              String fileName = "kjrjh20111103-BATCH2242_20111113-091337.txt";
              var startIndex = fileName.LastIndexOf('-') + 1;
              var length = fileName.LastIndexOf('.') - startIndex;
              var output = fileName.Substring(startIndex, length);
      

      【讨论】:

        猜你喜欢
        • 2012-01-24
        • 2011-08-22
        • 2010-12-15
        • 2018-04-21
        • 2015-02-01
        • 2011-05-11
        • 1970-01-01
        • 2015-12-01
        • 2020-02-04
        相关资源
        最近更新 更多