lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]



On 02/06/2008, at 1:25 PM, Roberto Ierusalimschy wrote:


You should have a look at the lpeg paper:

 A Text Pattern-Matching Tool based on Parsing Expression Grammars
 http://www.inf.puc-rio.br/~roberto/docs/peg.pdf

Thanks for the solution. I was indeed looking at the pdf file, which gave me the idea for:

  function make_wildcard (s)
    return lpeg.C((#-lpeg.P(s) * 1)^1) * (s)
  end -- make_wildcard

print ( lpeg.match (make_wildcard (" says "), "Nick says hello") ) --> Nick


However your proposal looks more elegant, especially the 2nd one, which can be modified to return the capture fairly easily:

 line = lpeg.P" says hello"
 p = lpeg.C((1 - line)^0) * line

 print (lpeg.match (p, "Nick says hello"))  --> Nick


Your solution can be further modified to solve the problem of <someone> says <something>


 line = lpeg.P " says "
 p = lpeg.C((1 - line)^1) * line * lpeg.C (lpeg.P(1)^1)

 print (lpeg.match (p, "Nick says hello"))  --> Nick hello


One question, would your solution of:

  line = lpeg.P" says hello"
  p = (1 - line)^0 * line

be more efficient if written as:

  line = lpeg.P" says hello"
  p = (1 - #line)^0 * line

I have added a "#" to "line" so as to consume no input, on the basis that "consuming input" might take more work than not doing so. Or is that irrelevant?

- Nick