[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.lisp

Re: reading between paranteses

William James

1/31/2016 4:48:00 PM

Barry Margolin wrote:

> >I'm not so good in Lisp but I need a function that reads the text
> >between two paranteses. f.expl. if we have the text:
> >
> >"there was (once a (little mouse) who went (across) the street) to the
> >other side"
> >
> >I need to extract the text:
> >
> >"once a (little mouse) who went (across) the street"
> >
> >The function must not stop by other paranteses inside the first
> >parantes.
>
> Untested:


I think that he didn't have CL (COBOL-Like) installed on his computer.
The language really wasn't worth using.


>
> (defconstant +open+ #\()
> (defconstant +close+ #\))
>
> (defun read-between-parens (string)
> (let ((paren-depth 1)
> (start (position +open+ string))
> end)
> (unless start
> (error "No open parenthesis in ~S" string))
> (setq end start)
> (loop
> (setq end (position-if #'(lambda (c)
> (or (char= c +open+)
> (char= c +close+)))
> string :start (1+ end)))
> (when (null end)
> (error "Unbalanced parentheses in ~S" string))
> (if (char= (char string end) +open+)
> (incf paren-depth)
> (decf paren-depth))
> (when (zerop paren-depth) ; Found the matching close paren
> (return (subseq string (1+ start) end))))))

MatzLisp (Ruby):

def find_closing_fence( opener, closer, string, pos=0)
pattern = Regexp.new('[' + opener + closer + ']')
depth = 1
pos -= 1
loop {
if pos = string.index(pattern, pos + 1)
depth += ((string[pos,1] == opener) ? 1 : -1)
return pos if depth.zero?
else
return nil
end}
end

def between_parentheses(text)
i = text.index("(") and j = find_closing_fence("(", ")", text, i+1)
j && text[i+1 .. j-1]
end

between_parentheses(
"there was (once a (mouse) who went (across) the street) to other side")
===>
"once a (mouse) who went (across) the street"

between_parentheses("once a (mouse")
===>
nil

between_parentheses("once a mouse")
===>
nil

--
[A]n unholy alliance of leftists, capitalists, and Zionist supremacists has
schemed to promote immigration and miscegenation with the deliberate aim of
breeding us out of existence in our own homelands.... [T]he real aim stays the
same: the biggest genocide in human history.... --- Nick Griffin
(https://www.youtube.com/watch?v=K...)