【问题标题】:Extracting substring based on the same identifier in two locations基于两个位置的相同标识符提取子字符串
【发布时间】:2018-05-24 00:50:05
【问题描述】:

我找到了this question,它实现了我想要的,但是我只有一个问题:子字符串的“开始”和“结束”是同一个字符。

我的字符串是:

.0.label unicode "Area - 110"

我想提取引号之间的文本(“Area - 110”)。

在链接的问题中,答案都是使用特定的标识符和IndexOf 解决方案。问题是如果我这样做,IndexOf 可能会返回相同的值。

另外,如果我使用Split 方法,我要保留的文本不是固定长度——可能是一个单词,可能是七个;所以我在指定该集合中第一个和最后一个单词的索引时也遇到了问题。

【问题讨论】:

  • 链接问题的正则表达式解决方案有什么问题? Regex.Match(input, @"(?<="")(.+?)(?="")"); 将匹配您的字符串,您将能够从它的值中提取 Area - 110

标签: c# .net string


【解决方案1】:

问题是,如果我这样做,IndexOf 可能会返回相同的值。

这种情况下的一个常见技巧是使用LastIndexOf 来查找结束双引号的位置:

int start = str.IndexOf('"');
int end = str.LastIndexOf('"');
if (start >= 0 && end > start) {
    // We have two separate locations
    Console.WriteLine(str.Substring(start+1, end-start-1));
}

Demo.

【讨论】:

    【解决方案2】:

    我会这样:

    string str = ".0.label unicode \"Area - 110\"";
    str = input.SubString(input.IndexOf("\"") + 1);
    str = input.SubString(0, input.IndexOf("\""));
    

    事实上,这是我最常用的辅助方法/扩展之一,因为它用途广泛:

    /// <summary>
    /// Isolates the text in between the parameters, exclusively, using invariant, case-sensitive comparison. 
    /// Both parameters may be null to skip either step. If specified but not found, a FormatException is thrown.
    /// </summary>
    public static string Isolate(this string str, string entryString, string exitString)
        {
            if (!string.IsNullOrEmpty(entryString))
            {
                int entry = str.IndexOf(entryString, StringComparison.InvariantCulture);
                if (entry == -1) throw new FormatException($"String.Isolate failed: \"{entryString}\" not found in string \"{str.Truncate(80)}\".");
                str = str.Substring(entry + entryString.Length);
            }
    
            if (!string.IsNullOrEmpty(exitString))
            {
                int exit = str.IndexOf(exitString, StringComparison.InvariantCulture);
                if (exit == -1) throw new FormatException($"String.Isolate failed: \"{exitString}\" not found in string \"{str.Truncate(80)}\".");
                str = str.Substring(0, exit);
            }
    
            return str;
        }
    

    你会这样使用它:

    string str = ".0.label unicode \"Area - 110\"";
    string output = str.Isolate("\"", "\"");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-05
      • 1970-01-01
      • 2013-09-14
      • 1970-01-01
      • 2021-08-30
      相关资源
      最近更新 更多