PageRenderTime 66ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/extension/luascript/lpeg-0.11/re.html

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