Re: regular expressions in Prolog

Michael Hendricks <[email protected]>
Newsgroups gmane.comp.ai.prolog.swi
Message-ID <CAFHuXuaZ_hNnK=SRtgO5Jy9KB8nUngrV7UE3Yf=6OnMvJ6qo0A@mail.gmail.com>
On Mon, Sep 16, 2013 at 10:34 AM, John Benson <[email protected]>wrote:

>  However, when I used it I got the following results:
>
>     130 ?- amatchesregexb('ab12cd', '.*([0-9]+).*', Result).
>     Result = ['2'].
>
>     131 ?- amatchesregexb('ab12cd', '[^0-9]*([0-9]+).*', Result).
>     Result = ['12'].
>
>     132 ?-
>
>
> *I expected the first example capture **([0-9]+) to cap**ture '12', but
> it only captured '2'.*
>
> I had to add [^0-9] infront of the numeric capture to successfully
> capture both digits '12'.
>
> I'm a Prolog newbie, and don'tunderstand the code that I copied.
>

This regex behavior is correct and isn't specific to Prolog.  A * matches
greedily.  That is, it consumes as many characters as possible while still
allowing the whole pattern to match.  In the first example, .* can consume
the 1 and the entire regex still matches.  Using [^0-9]* prevents that part
of the pattern from matching the 1.

-- 
Michael
-------------- next part --------------
HTML attachment scrubbed and removed
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.