There is a text file where logs are written, its lines look like

INFO 10-04 22:09:10 DataLayer 11 Log - userId = 1050.

We need to somehow break these strings into elements of a string array, so that each element of this array contains the necessary part of the data. And it looked like this:

["Info"]["10-04 22:09:10"]["DataLayer"]["11"]["Log"]["- userId = 1050."] where [] is each element of the array, I tried through Split ("") - I gave out 61 elements, with a bunch of elements containing just spaces. And I just need to highlight the words, everything is complicated by the fact that there are many spaces in the line, and it is not correct to split the spaces, as there are ordinary phrases where the space is not as a column separator, but as a simple speech space. How can this be solved?

  • one
    Look here (a similar task). - BlackWitcher
  • one
    You can first replace an indefinite number of spaces with a special character, for example \ t for tabbing using the regular expression s.replace (/ \ s + / g, "\ t") and then use split - Denis

1 answer 1

The String.Split method has several overloads. In particular, besides the separator, it accepts the number of rows returned and the option excluding blank lines.

 string text = @"INFO 10-04 22:09:10 DataLayer 11 Log - userId = 1050."; var result = text.Split(new char[] { ' ' }, 7, StringSplitOptions.RemoveEmptyEntries); 

This code will give almost what you need. Only the date and time will be in different elements of the array. I guess it will not be a problem to use them.

  • Only still there is "- userId = 1050." ... - andreycha
  • If separators are guaranteed to have more than one space, then the regular expression \ s {2,} can be used and only that should be considered as separators. - Denis
  • @Denis - That's right. However, even a regular schedule is not needed: a separator of two (or more) spaces " " can also String.Split used in String.Split . - Alexander Petrov
  • I looked again, if the author needs exactly as he wrote, then probably still split will not work at all because of the date. It's easier to use regular expressions with groups, then you can do all of the above despite the fact that the separator is a space in the date, and there is also one space between the date and the next field. - Denis