【问题标题】:Parse out text inside pipe delimeter in string [duplicate]解析字符串中管道分隔符内的文本[重复]
【发布时间】:2019-06-18 19:01:51
【问题描述】:

c# 我需要帮助将管道字符中的单词解析为字符串列表。

“您可以在入住前 |720| 之前免费取消。如果您在入住前 |720| 取消,您将需要支付 |407.74 美元|。”

字符串列表应包含两项。 720 和 407.74 美元。

谢谢

【问题讨论】:

  • string.Split。每一秒条目都可能是您想要的条目。
  • 我玩过变奏曲,你说得对。它始终是列表中的偶数元素。谢谢。

标签: c# regex parsing


【解决方案1】:
private static IEnumerable<string> GetStringsBetweenDelimiters(string str, char delimiter)
{
    int openingIndex = default; //index of the opening delimiter
    int closingIndex = -1; //starts from -1 as otherwise it would not work for string
                           //starting with delimiter

    while (true)
    {
        openingIndex = str.IndexOf(delimiter, closingIndex + 1);
        //it has to be +1'd as otherwise it would return closingIndex
        if (openingIndex < 0) yield break; //No more delimiters
        closingIndex = str.IndexOf(delimiter, openingIndex + 1);
        //+1'd for same reason as above
        if (closingIndex < 0) //No closing delimiter
            throw new InvalidOperationException("The given string has odd number of delimiters.");
        //Might just break as well?

        yield return str.Substring(openingIndex + 1, closingIndex - openingIndex - 1);
    }
}

当像GetStringsBetweenDelimiters(str, '|') 这样调用时,这个方法只会返回两个竖线字符之间的值。这种方法优于 string.Split(delimiter) 的优点是它不会分配不在管道字符之间的不必要的子字符串(You can cancel free of charge untilbefore check-in. You’ll be charged...),而且使用起来可能更简单。

测试:

foreach (string str in GetStringBetweenDelimiters(testStr, '|'))
{
    Console.WriteLine(str);
}

打印

720
407.74USD
720

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-12
    • 1970-01-01
    • 2023-04-07
    • 2012-04-29
    • 2019-04-02
    • 2021-12-18
    • 1970-01-01
    相关资源
    最近更新 更多