search with regular expression stuck at empty line

General questions about using TextPad

Moderators: AmigoJack, bbadmin, helios, MudGuard

Post Reply
Josy_F
Posts: 2
Joined: Thu Mar 25, 2010 6:31 am

search with regular expression stuck at empty line

Post by Josy_F »

Hi,
I was wondering why a special search pattern gets stuck at an empty line

my regular expression:

Code: Select all

^.*
the content of the document to search through:

Code: Select all

line1
line2

line4
line5
When placing the cursor at the beginning of first line and start searching with the mentioned regular expression, first and second lines match.
Selecting Find Next at the second line TextPad marks the third line and gets stuck there.
Even when Wrap sarches is activated Find Next leaves line number 3 never again.


Whats wrong with this regular expresseion?
THX
Josef
nvj1662
Posts: 53
Joined: Thu May 17, 2007 10:02 am

Post by nvj1662 »

Welcome to the forum Jose.

I can only confirm that I have reproduced your experiment and obtained the same results. I am using Textpad 5.3.1. I get that same result whether POSIX is On or OFF.
ben_josephs
Posts: 2464
Joined: Sun Mar 02, 2003 9:22 pm

Post by ben_josephs »

The regex .* matches any number of characters, including zero of them. The recogniser is greedy: it matches as many characters as possible. So when the cursor is at the beginning of a non-empty line it matches the whole line, and leaves the cursor at the end of that line. The next match is at the beginning of the next line.

However, when the cursor is at the beginning of an empty line, the regex matches zero characters, so the cursor doesn't move. Therefore the regex can match again where it is, without the cursor moving. So it matches zero characters again. And again, and again,...

There are three solutions to this.

(1) If you only want to match non-empty lines, use ^.+ instead of ^.*. Moral: Always use + unless you really need *.

(2) Use .* instead of ^.*. This solution uses two facts. (a) You don't need the ^ at the beginning of your regex. The recogniser is eager: it always matches as early as possible, which, in this case, is at the beginnings of lines. (b) .* on its own is handled as a special case: after matching once the recogniser moves the cursor one place on, so it doesn't get stuck.

(3) If you want to do a replacement, use Replace All. The algorithm that implements this also avoids the getting-stuck problem.
Josy_F
Posts: 2
Joined: Thu Mar 25, 2010 6:31 am

Post by Josy_F »

@ben_josephs,
thanks for the detailed description.

Things work great with your solution :D

THX Josef
Post Reply