-1

I have a string like this: string ip = "192.168.10.30 | SomeName". I want to split it by the | (including the spaces. With this code it is not possible unfortunately:

string[] address = ip.Split(new char[] {'|'}, StringSplitOptions.RemoveEmptyEntries);

as this leads to "192.168.10.30 ". I know I can add .Trim() to address[0] but is that really the right approach?

Simply adding the spaces(' | ') to the search pattern gives me an

Unrecognized escape sequence

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
PrimuS
  • 2,505
  • 6
  • 33
  • 66
  • 2
    You may want to use: https://msdn.microsoft.com/en-us/library/8yttk7sy(v=vs.110).aspx – Evan Trimboli Nov 10 '16 at 08:14
  • 1
    You might use regex with this pattern. `(?\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) *\| *(?\S*)`. for example to get ip write `regex.Match(input).Groups["ip"]` and to get name write name instead of ip – M.kazem Akhgary Nov 10 '16 at 08:23

3 Answers3

10

You can split by string, not by character:

var result = ip.Split(new string[] {" | "}, StringSplitOptions.RemoveEmptyEntries);
Uriil
  • 11,948
  • 11
  • 47
  • 68
  • 2
    The `char[] { '|',' '}` approach is more robust, as it covers the case of missing spaces and empty entries (which may or may not be relevant to the OP, but it's worth to know) – Konamiman Nov 10 '16 at 08:21
3

The Split method accepts character array, so you can specify the second character as well in that array. Since you ware used RemoveEmptyEntries those spaces will be removed from the final result.

Use like this :

 string[] address = ip.Split(new char[] { '|',' '}, StringSplitOptions.RemoveEmptyEntries);

You will get two items in the array

"192.168.10.30" and SomeName

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
0

This might do the trick for you

string[] address = ip.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToArray();
Mohit S
  • 13,723
  • 6
  • 34
  • 69