开发者

C# Regex Ignoring Escaped Character

I hav开发者_Go百科e 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.


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 \|"


Regex.Split(input, @"(?<!\\)\|");
  • (?<!\\) - negative lookbehind. There is no preceding \
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜