1

If I have a string like this

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

How do I extract the part that says "The second argument must be larger than the first."?

theonlygusti
  • 11,032
  • 11
  • 64
  • 119
  • 2
    If all your inputs are of same format then why don't you make a try with `.Substring()` by taking index of `ERROR` – sujith karivelil Dec 21 '16 at 03:12
  • @un-lucky could be `@"1024 WARNING Something something something..."` – theonlygusti Dec 21 '16 at 03:13
  • 1
    Get the index of the [2nd space](http://stackoverflow.com/questions/186653/c-sharp-indexof-the-nth-occurrence-of-a-string), then get the substring after that. Or someone can come along with regex probably. – Martheen Dec 21 '16 at 03:15
  • 1
    When in doubt, blame [RegEx](https://msdn.microsoft.com/en-us/library/hs600312(v=vs.110).aspx). Then you'll have two problems. – HABO Dec 21 '16 at 03:16

3 Answers3

4
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);

How ever this may potentially fail in various cases. for example having multiple spaces behind each other. using this method may be error-prone.

Regex is better option.

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();

You can add as many as patterns you want in your first capture.like this (ERROR|WARNING|HINT|etc)

M.kazem Akhgary
  • 18,645
  • 8
  • 57
  • 118
  • How do I convert message to a string? – theonlygusti Dec 21 '16 at 03:47
  • by calling `ToString()` will edit. btw `Match` method will return a `Match` . `Message` is a name I chose for the second group to be able to capture second group by name (so its more readable). – M.kazem Akhgary Dec 21 '16 at 03:50
  • @theonlygusti also you can have this Regex as `static` field. if this method is used frequently it is recommended to make `new Regex(...)` once and use it as much as you want. – M.kazem Akhgary Dec 21 '16 at 03:56
  • I ended up using the second solution, having the regex match groups was very useful in other parts of my program as well. – theonlygusti Dec 22 '16 at 22:58
2

Try this:

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

That gives me the result you're looking for.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172
1
var result = String.Join(" ",error.split(' ').Skip(2))

Or this

var output = Regex.Replace(ErrorText,@"\d+?\s\w+","");
Sateesh Pagolu
  • 9,282
  • 2
  • 30
  • 48