Kohei Nozaki's blog 

What are lookahead / lookbehind of regex?

Posted on Sunday Feb 15, 2015 at 10:04AM in Technology

I’m learning regex with Mastering Regular Expressions, 3rd Edition. it’s interesting because long time I didn’t understand lookahead / lookbehind correctly. so I leave some examples for better understanding. tests were ran against jEdit 5.2.0 on Oracle Java 1.8.0_31.

Given string

(1) http://blog1.example.com/roller/
(2) http://blog2.example.com/mt/
(3) http://blog3.example.com/wordpress/

Positive lookahead

Positive lookahead ensures that the matching has following fragment which matches to given regex inside parenthesis. example\.com(?=/roller/) matches against only (1).

19424ff6 37e1 4af4 b639 5f6b9d628950

Negative lookahead

Negative lookahead simply reverses that condition. example\.com(?!/roller/) matches against (2) and (3).

231b7831 62f4 4c91 af8e 45496304d2a6

Positive lookbehind

Positive lookbehind means that the matching has the preceding fragment which matches to given regex inside parenthesis. (?<=blog1\.)example\.com matches against only (1).

517be8f0 4b72 457a 8c18 29eb15e5aed2

Negative lookbehind

Negative lookbehind simply reverses that condition. (?<!blog1\.)example\.com matches against (2) and (3).

119dcddc 601b 4c02 a606 69dfd1bb5693

No one has commented yet.

Leave a Comment

HTML Syntax: NOT allowed