【问题标题】:get string after second space在第二个空格后获取字符串
【发布时间】:2017-05-06 09:18:42
【问题描述】:

如果我有这样的字符串

@"400 ERROR The second argument must be larger than the first."

如何提取"The second argument must be larger than the first." 的部分?

【问题讨论】:

  • 如果你所有的输入都是相同的格式,那么你为什么不尝试使用.Substring(),通过索引ERROR
  • @un-lucky 可能是@"1024 WARNING Something something something..."
  • 获取2nd space的索引,然后获取之后的子串。或者有人可能会使用正则表达式。
  • 如有疑问,请归咎于RegEx。那么你会遇到两个问题。

标签: c# string substring


【解决方案1】:
string error = @"400 ERROR The second argument must be larger than the first.";
var ind1 = error.IndexOf(' ');
var ind2 = error.IndexOf(' ', ind1 + 1);
var substring = error.Substring(ind2);

这在各种情况下可能会失败。例如,彼此后面有多个空格。使用这种方法可能容易出错。

正则表达式是更好的选择。

string error = @"400 ERROR The second argument must be larger than the first.";
Regex regex = new Regex("^\\d+ *(ERROR|WARNING) *(?<Message>.*)$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
var message = regex.Match(error).Groups["Message"].ToString();

您可以在第一次捕获中添加任意数量的模式。就像这个(ERROR|WARNING|HINT|etc)

【讨论】:

  • 如何将消息转换为字符串?
  • 通过调用ToString() 将进行编辑。顺便说一句 Match 方法将返回 MatchMessage 是我为第二组选择的名称,以便能够按名称捕获第二组(因此更具可读性)。
  • @theonlygusti 您也可以将此正则表达式作为static 字段。如果经常使用这种方法,建议制作一次new Regex(...),想用多少就用多少。
  • 我最终使用了第二种解决方案,正则表达式匹配组在我程序的其他部分也非常有用。
【解决方案2】:

试试这个:

var source = @"400 ERROR The second argument must be larger than the first.";
var result = String.Join(" ", source.Split(' ').Skip(2));

这给了我你正在寻找的结果。

【讨论】:

    【解决方案3】:
    var result = String.Join(" ",error.split(' ').Skip(2))
    

    或者这个

    var output = Regex.Replace(ErrorText,@"\d+?\s\w+","");
    

    【讨论】:

      猜你喜欢
      • 2021-12-01
      • 1970-01-01
      • 2015-06-06
      • 2021-08-13
      • 2016-03-26
      • 2022-06-17
      • 1970-01-01
      • 2021-10-15
      • 2011-12-10
      相关资源
      最近更新 更多