Re: Detecting the presence of a pattern in an atom
Jeff Rosenwald <[email protected]>
| Newsgroups | gmane.comp.ai.prolog.swi |
|---|---|
| Message-ID | <[email protected]> |
Hi Steve:
You need not be afraid of DCGs. In Prolog, they are among your best friends.
For example:
% Here's the DCG
nothing("") --> "".
upper_alpha(A) --> [A], { code_type(A, upper) }.
lparen --> "(".
rparen --> ")".
upper_alpha_string([ A | B]) -->
upper_alpha(A), (upper_alpha_string(B); nothing(B)).
parenthetic_phrase(A) -->
lparen, upper_alpha_string(A), rparen.
% Here's how you use it in your application.
% Convert string to codes before calling string_search/2.
string_search([], nil) :-
!, fail.
string_search(String, Atom) :-
phrase(parenthetic_phrase(Codes), String, _), !,
atom_codes(Atom, Codes).
string_search([_ | More], Atom) :-
string_search(More, Atom).
Tested:
?- string_search("acme ltd (HELLO) 123", X).
X = 'HELLO'.
Regards,
Jeff R.
-----Original Message-----
From: Carlo Capelli <[email protected]>
To: Steve Prior <[email protected]>
Cc: Prolog <[email protected]>
Sent: Tue, Oct 15, 2013 2:40 am
Subject: Re: [SWIPL] Detecting the presence of a pattern in an atom
2013/10/15 Steve Prior <[email protected]>
> This is not a homework problem.
>
> I've been writing code which retrieves a list of titles from a web page
> source and need to do a little pattern matching on each title. A title
> might look like:
>
> Some name and some business name (ABC)
>
> I'm trying to get the "ABC".
>
> The titles don't have any formal grammar to them, but for starters I need
> to see if there is a substring which starts with '(' contains all upper
> case letters and ends with ')'. I suppose it's possible that the title
> might contain multiple open/close parens, but I'd expect only one set to
> fit the all upper case criterion.
>
> It seems a bit much to do a DCG grammar for this and I know that a regex
> isn't the Prolog way of doing things, but don't remember what a better
> option would be. I'm a bit rusty in Prolog, I picked it for this project
> because of SWI's html parsing abilities which I've already put to good use.
>
>
Michael regex pack, or XPCE regexes are available.
?- regex('\\(([A-Z]+)\\)', [], 'acme ltd (HELLO) 123', [P]), format('~s',
[P]).
HELLO
P = [72, 69, 76, 76, 79]
HTH Carlo
> Any pointers?
>
> Steve
> ______________________________**_________________
> SWI-Prolog mailing list
> [email protected].**de <[email protected]>
> https://lists.iai.uni-bonn.de/**mailman/listinfo.cgi/swi-**prolog<https://lists.iai.uni-bonn.de/mailman/listinfo.cgi/swi-prolog>
>
-------------- next part --------------
HTML attachment scrubbed and removed
_______________________________________________
SWI-Prolog mailing list
[email protected]
https://lists.iai.uni-bonn.de/mailman/listinfo.cgi/swi-prolog
-------------- next part --------------
HTML attachment scrubbed and removed