2

I have a string like this that is delimited | and can contain any character in between:

"one two|three four five|six \| seven eight|nine"

I'd like to find a regex that returns:

one two
three four five
six | seven eight
nine

I can think about how I want to do this but, I don't know regex well enough. I basically want to match until I reach a | that is not preceded by a \. How do I do this? I know there is a back tracker, but I don't know how to do it.

2 Answers 2

3

Essentially you want to find instances of this pattern:

@"([^|\\]|\\.)+"

This matches:

  1. [^|\\] — Any character aside from a pipe or a backslash.
  2. \\. — Any character escaped with a backslash.
  3. (...|...)+ — One or more of the preceding (escaped) characters.

The \\. construct is nice because it lets you escape any character, in particular other backslashes. This lets you have a backslash at the end of a string, for example:

"backslash \\|forward slash /|pipe \|"
1
Regex.Split(input, @"(?<!\\)\|");
  • (?<!\\) - negative lookbehind. There is no preceding \
1
  • 1
    a single negative look behind does not parse an even number of preceding backslashes correctly. E.g. input: first \\| second<br> should return: first \\, then second Oct 19, 2016 at 18:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.