PageRenderTime 53ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/lpeg/re.html

https://bitbucket.org/ewing/luacocoa/
HTML | 486 lines | 443 code | 42 blank | 1 comment | 0 complexity | 7005ab25bdfff32543416d386bbce831 MD5 | raw file
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  2. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  3. <html>
  4. <head>
  5. <title>LPeg.re - Regex syntax for LPEG</title>
  6. <link rel="stylesheet"
  7. href="http://www.inf.puc-rio.br/~roberto/lpeg/doc.css"
  8. type="text/css"/>
  9. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  10. </head>
  11. <body>
  12. <!-- $Id: re.html,v 1.17 2011/01/10 15:08:06 roberto Exp $ -->
  13. <div id="container">
  14. <div id="product">
  15. <div id="product_logo">
  16. <a href="http://www.inf.puc-rio.br/~roberto/lpeg/">
  17. <img alt="LPeg logo" src="lpeg-128.gif"/>
  18. </a>
  19. </div>
  20. <div id="product_name"><big><strong>LPeg.re</strong></big></div>
  21. <div id="product_description">
  22. Regex syntax for LPEG
  23. </div>
  24. </div> <!-- id="product" -->
  25. <div id="main">
  26. <div id="navigation">
  27. <h1>re</h1>
  28. <ul>
  29. <li><a href="#basic">Basic Constructions</a></li>
  30. <li><a href="#func">Functions</a></li>
  31. <li><a href="#ex">Some Examples</a></li>
  32. <li><a href="#license">License</a></li>
  33. </ul>
  34. </li>
  35. </ul>
  36. </div> <!-- id="navigation" -->
  37. <div id="content">
  38. <h2><a name="basic"></a>The <code>re</code> Module</h2>
  39. <p>
  40. The <code>re</code> module
  41. (provided by file <code>re.lua</code> in the distribution)
  42. supports a somewhat conventional regex syntax
  43. for pattern usage within <a href="lpeg.html">LPeg</a>.
  44. </p>
  45. <p>
  46. The next table summarizes <code>re</code>'s syntax.
  47. A <code>p</code> represents an arbitrary pattern;
  48. <code>num</code> represents a number (<code>[0-9]+</code>);
  49. <code>name</code> represents an identifier
  50. (<code>[a-zA-Z][a-zA-Z0-9_]*</code>).
  51. Constructions are listed in order of decreasing precedence.
  52. <table border="1">
  53. <tbody><tr><td><b>Syntax</b></td><td><b>Description</b></td></tr>
  54. <tr><td><code>( p )</code></td> <td>grouping</td></tr>
  55. <tr><td><code>'string'</code></td> <td>literal string</td></tr>
  56. <tr><td><code>"string"</code></td> <td>literal string</td></tr>
  57. <tr><td><code>[class]</code></td> <td>character class</td></tr>
  58. <tr><td><code>.</code></td> <td>any character</td></tr>
  59. <tr><td><code>%name</code></td>
  60. <td>pattern <code>defs[name]</code> or a pre-defined pattern</td></tr>
  61. <tr><td><code>name</code></td><td>non terminal</td></tr>
  62. <tr><td><code>&lt;name&gt;</code></td><td>non terminal</td></tr>
  63. <tr><td><code>{}</code></td> <td>position capture</td></tr>
  64. <tr><td><code>{ p }</code></td> <td>simple capture</td></tr>
  65. <tr><td><code>{: p :}</code></td> <td>anonymous group capture</td></tr>
  66. <tr><td><code>{:name: p :}</code></td> <td>named group capture</td></tr>
  67. <tr><td><code>{~ p ~}</code></td> <td>substitution capture</td></tr>
  68. <tr><td><code>=name</code></td> <td>back reference
  69. </td></tr>
  70. <tr><td><code>p ?</code></td> <td>optional match</td></tr>
  71. <tr><td><code>p *</code></td> <td>zero or more repetitions</td></tr>
  72. <tr><td><code>p +</code></td> <td>one or more repetitions</td></tr>
  73. <tr><td><code>p^num</code></td> <td>exactly <code>n</code> repetitions</td></tr>
  74. <tr><td><code>p^+num</code></td>
  75. <td>at least <code>n</code> repetitions</td></tr>
  76. <tr><td><code>p^-num</code></td>
  77. <td>at most <code>n</code> repetitions</td></tr>
  78. <tr><td><code>p -&gt; 'string'</code></td> <td>string capture</td></tr>
  79. <tr><td><code>p -&gt; "string"</code></td> <td>string capture</td></tr>
  80. <tr><td><code>p -&gt; {}</code></td> <td>table capture</td></tr>
  81. <tr><td><code>p -&gt; name</code></td> <td>function/query/string capture
  82. equivalent to <code>p / defs[name]</code></td></tr>
  83. <tr><td><code>p =&gt; name</code></td> <td>match-time capture
  84. equivalent to <code>lpeg.Cmt(p, defs[name])</code></td></tr>
  85. <tr><td><code>& p</code></td> <td>and predicate</td></tr>
  86. <tr><td><code>! p</code></td> <td>not predicate</td></tr>
  87. <tr><td><code>p1 p2</code></td> <td>concatenation</td></tr>
  88. <tr><td><code>p1 / p2</code></td> <td>ordered choice</td></tr>
  89. <tr><td>(<code>name &lt;- p</code>)<sup>+</sup></td> <td>grammar</td></tr>
  90. </tbody></table>
  91. <p>
  92. Any space appearing in a syntax description can be
  93. replaced by zero or more space characters and Lua-style comments
  94. (<code>--</code> until end of line).
  95. </p>
  96. <p>
  97. Character classes define sets of characters.
  98. An initial <code>^</code> complements the resulting set.
  99. A range <em>x</em><code>-</code><em>y</em> includes in the set
  100. all characters with codes between the codes of <em>x</em> and <em>y</em>.
  101. A pre-defined class <code>%</code><em>name</em> includes all
  102. characters of that class.
  103. A simple character includes itself in the set.
  104. The only special characters inside a class are <code>^</code>
  105. (special only if it is the first character);
  106. <code>]</code>
  107. (can be included in the set as the first character,
  108. after the optional <code>^</code>);
  109. <code>%</code> (special only if followed by a letter);
  110. and <code>-</code>
  111. (can be included in the set as the first or the last character).
  112. </p>
  113. <p>
  114. Currently the pre-defined classes are similar to those from the
  115. Lua's string library
  116. (<code>%a</code> for letters,
  117. <code>%A</code> for non letters, etc.).
  118. There is also a class <code>%nl</code>
  119. containing only the newline character,
  120. which is particularly handy for grammars written inside long strings,
  121. as long strings do not interpret escape sequences like <code>\n</code>.
  122. </p>
  123. <h2><a name="func">Functions</a></h2>
  124. <h3><code>re.compile (string, [, defs])</code></h3>
  125. <p>
  126. Compiles the given string and
  127. returns an equivalent LPeg pattern.
  128. The given string may define either an expression or a grammar.
  129. The optional <code>defs</code> table provides extra Lua values
  130. to be used by the pattern.
  131. </p>
  132. <h3><code>re.find (subject, pattern [, init])</code></h3>
  133. <p>
  134. Searches the given pattern in the given subject.
  135. If it finds a match,
  136. returns the index where this occurrence starts,
  137. plus the captures made by the pattern (if any).
  138. Otherwise, returns nil.
  139. </p>
  140. <p>
  141. An optional numeric argument <code>init</code> makes the search
  142. starts at that position in the subject string.
  143. As usual in Lua libraries,
  144. a negative value counts from the end.
  145. </p>
  146. <h3><code>re.match (subject, pattern)</code></h3>
  147. <p>
  148. Matches the given pattern against the given subject.
  149. </p>
  150. <h3><code>re.updatelocale ()</code></h3>
  151. <p>
  152. Updates the pre-defined character classes to the current locale.
  153. </p>
  154. <h2><a name="ex">Some Examples</a></h2>
  155. <h3>A complete simple program</h3>
  156. <p>
  157. The next code shows a simple complete Lua program using
  158. the <code>re</code> module:
  159. </p>
  160. <pre class="example">
  161. local re = require"re"
  162. -- find the position of the first number in a string
  163. print(re.find("the number 423 is odd", "[0-9]+")) --&gt; 12
  164. -- similar, but also captures (and returns) the number
  165. print(re.find("the number 423 is odd", "{[0-9]+}")) --&gt; 12 423
  166. -- returns all words in a string
  167. print(re.match("the number 423 is odd", "({%a+} / .)*"))
  168. --&gt; the number is odd
  169. </pre>
  170. <h3>Balanced parentheses</h3>
  171. <p>
  172. The following call will produce the same pattern produced by the
  173. Lua expression in the
  174. <a href="lpeg.html#balanced">balanced parentheses</a> example:
  175. </p>
  176. <pre class="example">
  177. b = re.compile[[ balanced &lt;- "(" ([^()] / balanced)* ")" ]]
  178. </pre>
  179. <h3>String reversal</h3>
  180. <p>
  181. The next example reverses a string:
  182. </p>
  183. <pre class="example">
  184. rev = re.compile[[ R &lt;- (!.) -&gt; '' / ({.} R) -&gt; '%2%1']]
  185. print(rev:match"0123456789") --&gt; 9876543210
  186. </pre>
  187. <h3>CSV decoder</h3>
  188. <p>
  189. The next example replicates the <a href="lpeg.html#CSV">CSV decoder</a>:
  190. </p>
  191. <pre class="example">
  192. record = re.compile[[
  193. record &lt;- ( field (',' field)* ) -&gt; {} (%nl / !.)
  194. field &lt;- escaped / nonescaped
  195. nonescaped &lt;- { [^,"%nl]* }
  196. escaped &lt;- '"' {~ ([^"] / '""' -&gt; '"')* ~} '"'
  197. ]]
  198. </pre>
  199. <h3>Lua's long strings</h3>
  200. <p>
  201. The next example matches Lua long strings:
  202. </p>
  203. <pre class="example">
  204. c = re.compile([[
  205. longstring &lt;- ('[' {:eq: '='* :} '[' close) -&gt; void
  206. close &lt;- ']' =eq ']' / . close
  207. ]], {void = function () end})
  208. print(c:match'[==[]]===]]]]==]===[]') --&gt; 17
  209. </pre>
  210. <h3>Abstract Syntax Trees</h3>
  211. <p>
  212. This example shows a simple way to build an
  213. abstract syntax tree (AST) for a given grammar.
  214. To keep our example simple,
  215. let us consider the following grammar
  216. for lists of names:
  217. </p>
  218. <pre class="example">
  219. p = re.compile[[
  220. listname &lt;- (name s)*
  221. name &lt;- [a-z][a-z]*
  222. s &lt;- %s*
  223. ]]
  224. </pre>
  225. <p>
  226. Now, we will add captures to build a corresponding AST.
  227. As a first step, the pattern will build a table to
  228. represent each non terminal;
  229. terminals will be represented by their corresponding strings:
  230. </p>
  231. <pre class="example">
  232. c = re.compile[[
  233. listname &lt;- (name s)* -&gt; {}
  234. name &lt;- {[a-z][a-z]*} -&gt; {}
  235. s &lt;- %s*
  236. ]]
  237. </pre>
  238. <p>
  239. Now, a match against <code>"hi hello bye"</code>
  240. results in the table
  241. <code>{{"hi"}, {"hello"}, {"bye"}}</code>.
  242. </p>
  243. <p>
  244. For such a simple grammar,
  245. this AST is more than enough;
  246. actually, the tables around each single name
  247. are already overkilling.
  248. More complex grammars,
  249. however, may need some more structure.
  250. Specifically,
  251. it would be useful if each table had
  252. a <code>tag</code> field telling what non terminal
  253. that table represents.
  254. We can add such a tag using
  255. <a href="lpeg.html/#cap-g">named group captures</a>:
  256. </p>
  257. <pre class="example">
  258. x = re.compile[[
  259. listname <- ({:tag: '' -> 'list':} (name s)*) -> {}
  260. name <- ({:tag: '' -> 'id':} {[a-z][a-z]*}) -> {}
  261. s <- ' '*
  262. ]]
  263. </pre>
  264. <p>
  265. With these group captures,
  266. a match against <code>"hi hello bye"</code>
  267. results in the following table:
  268. </p>
  269. <pre class="example">
  270. {tag="list",
  271. {tag="id", "hi"},
  272. {tag="id", "hello"},
  273. {tag="id", "bye"}
  274. }
  275. </pre>
  276. <h3>Indented blocks</h3>
  277. <p>
  278. This example breaks indented blocks into tables,
  279. respecting the indentation:
  280. </p>
  281. <pre class="example">
  282. p = re.compile[[
  283. block &lt;- ({:ident:' '*:} line
  284. ((=ident !' ' line) / &(=ident ' ') block)*) -&gt; {}
  285. line &lt;- {[^%nl]*} %nl
  286. ]]
  287. </pre>
  288. <p>
  289. As an example,
  290. consider the following text:
  291. </p>
  292. <pre class="example">
  293. t = p:match[[
  294. first line
  295. subline 1
  296. subline 2
  297. second line
  298. third line
  299. subline 3.1
  300. subline 3.1.1
  301. subline 3.2
  302. ]]
  303. </pre>
  304. <p>
  305. The resulting table <code>t</code> will be like this:
  306. </p>
  307. <pre class="example">
  308. {'first line'; {'subline 1'; 'subline 2'; ident = ' '};
  309. 'second line';
  310. 'third line'; { 'subline 3.1'; {'subline 3.1.1'; ident = ' '};
  311. 'subline 3.2'; ident = ' '};
  312. ident = ''}
  313. </pre>
  314. <h3>Macro expander</h3>
  315. <p>
  316. This example implements a simple macro expander.
  317. Macros must be defined as part of the pattern,
  318. following some simple rules:
  319. </p>
  320. <pre class="example">
  321. p = re.compile[[
  322. text &lt;- {~ item* ~}
  323. item &lt;- macro / [^()] / '(' item* ')'
  324. arg &lt;- ' '* {~ (!',' item)* ~}
  325. args &lt;- '(' arg (',' arg)* ')'
  326. -- now we define some macros
  327. macro &lt;- ('apply' args) -&gt; '%1(%2)'
  328. / ('add' args) -&gt; '%1 + %2'
  329. / ('mul' args) -&gt; '%1 * %2'
  330. ]]
  331. print(p:match"add(mul(a,b), apply(f,x))") --&gt; a * b + f(x)
  332. </pre>
  333. <p>
  334. A <code>text</code> is a sequence of items,
  335. wherein we apply a substitution capture to expand any macros.
  336. An <code>item</code> is either a macro,
  337. any character different from parentheses,
  338. or a parenthesized expression.
  339. A macro argument (<code>arg</code>) is a sequence
  340. of items different from a comma.
  341. (Note that a comma may appear inside an item,
  342. e.g., inside a parenthesized expression.)
  343. Again we do a substitution capture to expand any macro
  344. in the argument before expanding the outer macro.
  345. <code>args</code> is a list of arguments separated by commas.
  346. Finally we define the macros.
  347. Each macro is a string substitution;
  348. it replaces the macro name and its arguments by its corresponding string,
  349. with each <code>%</code><em>n</em> replaced by the <em>n</em>-th argument.
  350. </p>
  351. <h3>Patterns</h3>
  352. <p>
  353. This example shows the complete syntax
  354. of patterns accepted by <code>re</code>.
  355. </p>
  356. <pre class="example">
  357. p = [=[
  358. pattern &lt;- exp !.
  359. exp &lt;- S (alternative / grammar)
  360. alternative &lt;- seq ('/' S seq)*
  361. seq &lt;- prefix*
  362. prefix &lt;- '&amp;' S prefix / '!' S prefix / suffix
  363. suffix &lt;- primary S (([+*?]
  364. / '^' [+-]? num
  365. / '-&gt;' S (string / '{}' / name)
  366. / '=&gt;' S name) S)*
  367. primary &lt;- '(' exp ')' / string / class / defined
  368. / '{:' (name ':')? exp ':}'
  369. / '=' name
  370. / '{}'
  371. / '{~' exp '~}'
  372. / '{' exp '}'
  373. / '.'
  374. / name S !arrow
  375. / '&lt;' name '&gt;' -- old-style non terminals
  376. grammar &lt;- definition+
  377. definition &lt;- name S arrow exp
  378. class &lt;- '[' '^'? item (!']' item)* ']'
  379. item &lt;- defined / range / .
  380. range &lt;- . '-' [^]]
  381. S &lt;- (%s / '--' [^%nl]*)* -- spaces and comments
  382. name &lt;- [A-Za-z][A-Za-z0-9_]*
  383. arrow &lt;- '&lt;-'
  384. num &lt;- [0-9]+
  385. string &lt;- '"' [^"]* '"' / "'" [^']* "'"
  386. defined &lt;- '%' name
  387. ]=]
  388. print(re.match(p, p)) -- a self description must match itself
  389. </pre>
  390. <h2><a name="license">License</a></h2>
  391. <p>
  392. Copyright &copy; 2008-2010 Lua.org, PUC-Rio.
  393. </p>
  394. <p>
  395. Permission is hereby granted, free of charge,
  396. to any person obtaining a copy of this software and
  397. associated documentation files (the "Software"),
  398. to deal in the Software without restriction,
  399. including without limitation the rights to use,
  400. copy, modify, merge, publish, distribute, sublicense,
  401. and/or sell copies of the Software,
  402. and to permit persons to whom the Software is
  403. furnished to do so,
  404. subject to the following conditions:
  405. </p>
  406. <p>
  407. The above copyright notice and this permission notice
  408. shall be included in all copies or substantial portions of the Software.
  409. </p>
  410. <p>
  411. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  412. EXPRESS OR IMPLIED,
  413. INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  414. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  415. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  416. DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  417. TORT OR OTHERWISE, ARISING FROM,
  418. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  419. THE SOFTWARE.
  420. </p>
  421. </div> <!-- id="content" -->
  422. </div> <!-- id="main" -->
  423. <div id="about">
  424. <p><small>
  425. $Id: re.html,v 1.17 2011/01/10 15:08:06 roberto Exp $
  426. </small></p>
  427. </div> <!-- id="about" -->
  428. </div> <!-- id="container" -->
  429. </body>
  430. </html>