Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx Negative Lookahead Replacement Excluding Starting and Ending Pattern

Tags:

regex

vba

I am using RegEx in VBA and trying to replace any character that is not a vertical pipe within a beginning and ending vertical pipe.

In other words, my text looks like this:

++++|+++This|Is|An|Example++|++++

I only want to replace the non-pipe characters that appear after the first pipe and before the last pipe.

So, using an "a" as the replacement character for example:

++++|aaaaaaa|aa|aa|aaaaaaaaa|++++

I've tried a negative lookahead (the VBA implementation of RegEx doesn't support lookbehind), and while it works for excluding the characters after the last pipe from replacement, those before the first pipe still get replaced:

(?!^ *\|)[^\|](?! *$)

aaa|aaaaaaa|aa|aa|aaaaaaaaa|++++

I'm obviously not understanding the negative lookahead correctly because I can't seem to get those characters that appear prior to the first pipe to be excluded from the match.

Can someone please help me with this?

like image 405
AskingAQuestion Avatar asked Sep 20 '25 16:09

AskingAQuestion


1 Answers

If data follows the pattern (always at least two vertical pipes) here an idea with optional first part:

(^[^|]*\|)?[^|](?=[^|]*\|)

See this demo at regex101 (used \n in demo for not skipping lines) - replace with $1a

The part until the first pipe is captured to the first group $1 and inserted in replacement.
The lookahead checks after each [^|] (negated class) if there is another | pipe ahead.

like image 131
bobble bubble Avatar answered Sep 22 '25 07:09

bobble bubble