re.html 14 KB

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