3

I'm trying to write a RegEx to only match instances of the 'pipe' character (|) that are NOT followed by one or more further pipes. So a pipe followed by anything other than a pipe.

I have this but it doesn't appear to be working:

/|(?!/|) 
1
  • Update: This is matching pipes not followed by a pipe but I need it to also not match where there is a pipe BEFORE also. \|(?!\|) Commented Feb 7, 2013 at 16:24

3 Answers 3

6

You are escaping your pipe wrongly. You need to use backslash, and not slash. Apart from that, you also need to use negative look-behind, so that the last pipe is not matched, which is probably not preceded by a pipe, but not followed by it: -

(?<!\|)\|(?!\|) 

Generally, I prefer to use character class rather than escaping if I want to match regex meta-character class: -

(?<![|])[|](?![|]) 

But, it's my taste.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! However this is now matching double pipes too. I only want to match a pipe not followed by a pipe.
1

Okay, I found the answer, after much iteration. This will match ONLY a single pipe character not proceeded AND not followed by a pipe.

(?=(\|(?!\|)))((?<!\|)\|) 

1 Comment

This is the same as Rohit's answer, only less readable. You should accept that one.
0

Match a (start of line or a non-pipe) a pipe (an end of line or a non-pipe).

(^|[^|])[|]([^|]|$) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.