Regex.Split with a pipe | as separator
-
I wanted to use the Regex.Split function to split an incoming string up. The problem is that the string parts are separated by a pipe
|
but the pipe is used inside the Split function to split different separators (e.g. if you want to split on dash and space you would write it as" |-"
). So when I use"|"
the string splits into it's characters. I tried using"\|"
but this is considered an Unrecognized Escape Character and doesn't compile. Does anyone know if this is possible in another way? -
I wanted to use the Regex.Split function to split an incoming string up. The problem is that the string parts are separated by a pipe
|
but the pipe is used inside the Split function to split different separators (e.g. if you want to split on dash and space you would write it as" |-"
). So when I use"|"
the string splits into it's characters. I tried using"\|"
but this is considered an Unrecognized Escape Character and doesn't compile. Does anyone know if this is possible in another way?You have to encode the characters in the expression twice. First you have to encode the pipe to put it in the regular expression, then you have to encode the regular expression to put it in a literal string in the code. Use \\| in a regular literal string, or \| in an @ delimited string. Example:
string pattern = "\\|";
orstring pattern = @"\|";
Despite everything, the person most likely to be fooling you next is yourself.
-
You have to encode the characters in the expression twice. First you have to encode the pipe to put it in the regular expression, then you have to encode the regular expression to put it in a literal string in the code. Use \\| in a regular literal string, or \| in an @ delimited string. Example:
string pattern = "\\|";
orstring pattern = @"\|";
Despite everything, the person most likely to be fooling you next is yourself.