SXI Forum

A place to collect usefull tips, tricks and implementation strategies.

You are not logged in.

#1 24-01-2020 10:13:50

MarekR
Member
Registered: 21-02-2019
Posts: 19

Regex: Find Last Occurrence(Negative Lookahead)

Negative lookahead is used when you want to match something not followed by something else. We use this to find the last occurrence of a word in a string.

You can test all the below using Regex101.

The Regex looks as follows:

Word1(?!.*Word2)

"Word1" and "Word2" can be replaced with the relevant strings.

The regex finds the "Word1" you want to match and looks ahead in the string to see if "Word2" is found. If "Word2" is found it will not match. For example:

This Word1 will not match, because Word2 is ahead of it. However this Word1 will match.

This means If "Word1" and "Word2" are the same in the regular expression the last occurrence will match.

Example regex 1:

Test(?!.*Test)

Example Test String:

This Test must not match, however this Test should match.

The reason the first "Test" does not match is because "Test" is ahead of it. However the last "Test" matches because there is no "Test" ahead of it in the string.

Multiple line Negative Lookahead

If there is a line break multiple matches could be made, because the above regex works on a line to line basis.

If there is a multi line string use the following regex:

Example regex 2:

(?s:.*\s)\KTest(?!.*Test)

NB* I would recommend always using Example regex 2 because you can also use it for a single line string.

Example regex 2 does the same as Example regex 1, however it works for multi line strings. For example:

This Test must not match.

Neither should this Test.

This Test will match. 

Last edited by MarekR (24-01-2020 10:21:54)

Offline

Board footer

Powered by FluxBB