【发布时间】: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." 的部分?
【问题讨论】:
如果我有这样的字符串
@"400 ERROR The second argument must be larger than the first."
如何提取"The second argument must be larger than the first." 的部分?
【问题讨论】:
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 方法将返回 Match 。 Message 是我为第二组选择的名称,以便能够按名称捕获第二组(因此更具可读性)。
static 字段。如果经常使用这种方法,建议制作一次new Regex(...),想用多少就用多少。
试试这个:
var source = @"400 ERROR The second argument must be larger than the first.";
var result = String.Join(" ", source.Split(' ').Skip(2));
这给了我你正在寻找的结果。
【讨论】:
var result = String.Join(" ",error.split(' ').Skip(2))
或者这个
var output = Regex.Replace(ErrorText,@"\d+?\s\w+","");
【讨论】: