简体   繁体   English

从C#中的较长字符串解析此数字的最佳方法是什么?

[英]What is the best way to parse this number from the longer string in C#?

I have the following example strings 我有以下示例字符串

"CTS3010 - 6ppl"

or 要么

"CTs3200 - 14ppl"

or 要么

 "CTS-500 2ppl"

and i need to parse out the number from these strings. 我需要解析这些字符串中的数字。 What is the best way to parse out the number before the "ppl" at the end of the string. 在字符串末尾的“ppl”之前解析数字的最佳方法是什么。 Do i need regex? 我需要正则表达式吗? I have logic to loop backward but it feels like there is a more elegant solution here. 我有向后循环的逻辑,但是感觉这里有一个更优雅的解决方案。

These are just examples but all examples seem to follow the same pattern being 这些只是示例,但所有示例似乎都遵循相同的模式

  • A bunch of text 一堆文字
  • A number 一个号码
  • ppl suffix ppl后缀

You can do this to grab the number right before "ppl": 您可以执行此操作以在“ppl”之前获取数字:

using System.Text.RegularExpressions;
...

Regex regex = new Regex("([0-9]+)ppl");
string matchedValue = regex.Match("CTS-500 122ppl").Groups[1].Value;

In this case matchedValue will be 122. 在这种情况下, matchedValue将为122。

If you want to be safe, and you know "ppl" will always be at the end of the string, I would change the Regex to: "([0-9]+)ppl$" (the only difference is the dollar sign at the end). 如果你想要安全,并且你知道“ppl”将始终在字符串的末尾,我会将正则表达式更改为: "([0-9]+)ppl$" (唯一的区别是美元符号在末尾)。

Here's one way using LINQ: 这是使用LINQ的一种方式:

const String ppl = "ppl";
var examples = new[] { "CTS3010 - 6ppl", "CTs3200 - 14ppl", "CTS-500 2ppl" };
var delimiters = new[] { " " };
var result = examples
    .Select(e => e.Split(delimiters, StringSplitOptions.RemoveEmptyEntries))
    .Select(t => t.Last().ToLowerInvariant().Replace(ppl, String.Empty))
    .Select(Int32.Parse)
    .ToList();

Note that this will fail if it can't parse the integer value. 请注意,如果无法解析整数值,此操作将失败。 If you can't guarantee each string will end with NNppl you'll need to check that it is a numeric value first. 如果您不能保证每个字符串都以NNppl结尾, NNppl您需要先检查它是否为数字值。

I dunno about the "best way" but one method that is very easy to understand and modify is an extension method for a string object: 我不知道“最佳方法”,但是一种很容易理解和修改的方法是字符串对象的扩展方法:

 public static int Parse(this string phrase)
    {
        if (string.IsNullOrWhiteSpace(phrase)) { throw new NullReferenceException("phrase is null");}

        string num = string.Empty;
        foreach (char c in phrase.Trim().ToCharArray()) {
            if (char.IsWhiteSpace(c)) { break; }
            if (char.IsDigit(c)) { num += c.ToString(); }
        }
        return int.Parse(num);
    }

Assumes " " is the break condition. 假设“”是休息状态。 You may prefer int.TryParse if there is some chance you don't get a number and/or maybe a System.Text.StringBuilder. 如果您可能无法获得数字和/或System.Text.StringBuilder,则可能更喜欢int.TryParse。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM