c# - 在 C# 中从具有固定模式的字符串中提取特定数字

标签 c# string

这听起来像是一个非常基本的问题,但它给我在 C# 中带来了很多麻烦。

例如,假设我有以下 String 称为我的 chosenTarget.title:

2008/SD128934 - Wordz aaaaand more words (1233-26-21)
20998/AD1234 - Wordz and less words (1263-21-21)
208/ASD12345 - Wordz and more words (1833-21-21)

现在如您所见,所有三个 String 在某些方面是不同的。

我需要的是提取这些 String 的一个非常具体的部分,但让我感到困惑的是正确的微妙之处,我想知道你们中的一些人是否比我更了解。

我所知道的是 String 总是以下列模式出现:

yearNumber + "/"+ aFewLetters + theDesiredNumber + "- "+ descriptiveText + "("+ someDate + ")"

在上面的例子中,我想要返回给我的是:

128934
1234
12345

我需要提取theDesiredNumber

现在,我并不(那么)懒惰,所以我自己做了一些尝试:

var a = chosenTarget.title.Substring(chosenTarget.title.IndexOf("/") + 1, chosenTarget.title.Length - chosenTarget.title.IndexOf("/"));

所做的是切掉 yearNumber/,在 theDesiredNumber 之前留下 aFewLetter

然而,我很难正确地移除其余部分,我想知道你们中是否有人可以帮助我解决这个问题?

最佳答案

听起来好像只需要提取以-结尾的第一个/后面的数字。您可以结合使用字符串方法和 LINQ:

int startIndex = str.IndexOf("/");
string number = null;
if (startIndex >= 0 )
{
    int endIndex = str.IndexOf(" - ", startIndex);
    if (endIndex >= 0)
    {
        startIndex++;
        string token = str.Substring(startIndex, endIndex - startIndex); // SD128934
        number = String.Concat(token.Where(char.IsDigit)); // 128934
    }
}

另一种主要使用 String.Split 的 LINQ 方法:

number = String.Concat(
            str.Split(new[] { " - " }, StringSplitOptions.None)[0]
              .Split('/')
              .Last()
              .Where(char.IsDigit));

关于c# - 在 C# 中从具有固定模式的字符串中提取特定数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35479274/

相关文章:

c# - C# 中的 "Dictionary nest"?

c# - 一段时间后摘要身份验证 token 无效

C# Winforms WebBrowser 在默认浏览器中打开链接

c# - ASP.NET CORE 文件上传问题

html - 如何在iOS中对html格式的字符串应用粗体?

c++ - 字符指针在内存中的存储

javascript - 使用按值删除元素的自定义方法扩展数组

c++ - char数组的左移操作

c# - iOS 15 更新后 iOS 平台 Xamarin.forms 中的导航栏颜色变化问题

java - 帮助编写字符串的正则表达式