Skip to content

Instantly share code, notes, and snippets.

@YumaInaura
Last active August 31, 2018 10:58
Show Gist options
  • Save YumaInaura/e46210706ef0fcb0a9beb9b92f458046 to your computer and use it in GitHub Desktop.
Save YumaInaura/e46210706ef0fcb0a9beb9b92f458046 to your computer and use it in GitHub Desktop.
Regex — Remember Lookbehind Sun and Lookahead Moon

Regex — Remember Lookbehind Sun and Lookahead Moon

How to remember lookbehind and lookahead regular expression.

Now I show some pictures for my expression.

There is regular expression

image

You know caret means start

image

And dollar means end

image

If a caret is day

image

Then a dollar is night

image

Time advances from day to night

Because regex match advances from left to right means start to end.

image

Take a Time

image

You know regex lookahead and lookbehind?

I will express by same way about 4.

image

Let's be friend with mysterious marks

image

Umm take a Time second time

image

Behind means like Start and Head means like End

image

Time advances in same world

image

In the first place we can ignore question mark

Because it is common mark of starting special regex syntax.

image

Equal means Yes

image

Bang means No

image

"Positive Lookbehind" has "An toward past" and says "Yes".

image

image

"Negative Lookbehind" has a "An toward past" and says "No".

image

"Positive Lookahead" has no mark about time advance

image

But now imagine omitted mark toward Head.

Because time advances toward head is very natural.

So we do not have to express about it.

image

"Pegative Lookahead" has omitted mark toward head and says "Yes".

image

"Negative Lookahead" has omitted mark toward head and says "No".

image

Examples

Replace "B" with "X" in "ABC".

Positive Lookbehind

$ echo "ABC" | perl -pe 's/(?<=A)B/X/g'
AXC

Negative Lookbehind

$ echo "ABC" | perl -pe 's/(?<!A)B/X/g'
ABC

Positive Lookhead

$ echo "ABC" | perl -pe 's/B(?=C)/X/g'
AXC

Negative Lookhead

$ echo "ABC" | perl -pe 's/B(?!C)/X/g'
ABC

Versions

  • bash-4.4
  • perl 5, version 28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment