【问题标题】:Extract numbers from a string into an array in c# [duplicate]在c#中将字符串中的数字提取到数组中[重复]
【发布时间】:2020-09-22 05:45:27
【问题描述】:

我有一个字符串,它是一串 id --> "[6947,7182]"

我想将数字提取到一个数组中,并且还想保持简单,因为包含的 id 数量可能很多。

我列出了一个我尝试过的选项:

Regex.Split(this.request["ids"],@"\D+")

result :
{string[4]}
    [0]: ""
    [1]: "6947"
    [2]: "7182"
    [3]: ""


这在索引 0 和 3 处为我提供了额外的两个值,这是任何替代方法或任何更好的方法。

【问题讨论】:

  • 这看起来像 JSON。 (它一个有效的 JSON 字符串,可以被解析为一个包含两个整数的数组。)在 C# 中可能有一些解析 JSON 的方法。
  • 不,这不是 json !
  • 在 Api 内部,我们以这种方式传递信息
  • Regex.Matches(str, @"\d+").Cast<Match>().Select(x => x.Value)
  • 使用JsonConvert.DeserializeObject<List<int>>(string)将字符串转换为整数列表

标签: c# .net regex type-conversion


【解决方案1】:

这将得到一个字符串数组:

ids.Substring(1, ids.Length - 2).Split(',')

【讨论】:

    猜你喜欢
    • 2015-03-23
    • 2013-03-09
    • 2011-12-13
    • 2015-05-03
    • 2017-01-16
    • 2018-12-14
    • 2015-03-27
    • 1970-01-01
    • 2017-05-22
    相关资源
    最近更新 更多