]> git.lizzy.rs Git - rust.git/blob - src/libregex/lib.rs
Update to 0.11.0
[rust.git] / src / libregex / lib.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! This crate provides a native implementation of regular expressions that is
12 //! heavily based on RE2 both in syntax and in implementation. Notably,
13 //! backreferences and arbitrary lookahead/lookbehind assertions are not
14 //! provided. In return, regular expression searching provided by this package
15 //! has excellent worst case performance. The specific syntax supported is
16 //! documented further down.
17 //!
18 //! This crate's documentation provides some simple examples, describes Unicode
19 //! support and exhaustively lists the supported syntax. For more specific
20 //! details on the API, please see the documentation for the `Regex` type.
21 //!
22 //! # First example: find a date
23 //!
24 //! General use of regular expressions in this package involves compiling an
25 //! expression and then using it to search, split or replace text. For example,
26 //! to confirm that some text resembles a date:
27 //!
28 //! ```rust
29 //! use regex::Regex;
30 //! let re = match Regex::new(r"^\d{4}-\d{2}-\d{2}$") {
31 //!     Ok(re) => re,
32 //!     Err(err) => fail!("{}", err),
33 //! };
34 //! assert_eq!(re.is_match("2014-01-01"), true);
35 //! ```
36 //!
37 //! Notice the use of the `^` and `$` anchors. In this crate, every expression
38 //! is executed with an implicit `.*?` at the beginning and end, which allows
39 //! it to match anywhere in the text. Anchors can be used to ensure that the
40 //! full text matches an expression.
41 //!
42 //! This example also demonstrates the utility of raw strings in Rust, which
43 //! are just like regular strings except they are prefixed with an `r` and do
44 //! not process any escape sequences. For example, `"\\d"` is the same
45 //! expression as `r"\d"`.
46 //!
47 //! # The `regex!` macro
48 //!
49 //! Rust's compile time meta-programming facilities provide a way to write a
50 //! `regex!` macro which compiles regular expressions *when your program
51 //! compiles*. Said differently, if you only use `regex!` to build regular
52 //! expressions in your program, then your program cannot compile with an
53 //! invalid regular expression. Moreover, the `regex!` macro compiles the
54 //! given expression to native Rust code, which makes it much faster for
55 //! searching text.
56 //!
57 //! Since `regex!` provides compiled regular expressions that are both safer
58 //! and faster to use, you should use them whenever possible. The only
59 //! requirement for using them is that you have a string literal corresponding
60 //! to your expression. Otherwise, it is indistinguishable from an expression
61 //! compiled at runtime with `Regex::new`.
62 //!
63 //! To use the `regex!` macro, you must enable the `phase` feature and import
64 //! the `regex_macros` crate as a syntax extension:
65 //!
66 //! ```rust
67 //! #![feature(phase)]
68 //! #[phase(plugin)]
69 //! extern crate regex_macros;
70 //! extern crate regex;
71 //!
72 //! fn main() {
73 //!     let re = regex!(r"^\d{4}-\d{2}-\d{2}$");
74 //!     assert_eq!(re.is_match("2014-01-01"), true);
75 //! }
76 //! ```
77 //!
78 //! There are a few things worth mentioning about using the `regex!` macro.
79 //! Firstly, the `regex!` macro *only* accepts string *literals*.
80 //! Secondly, the `regex` crate *must* be linked with the name `regex` since
81 //! the generated code depends on finding symbols in the `regex` crate.
82 //!
83 //! The only downside of using the `regex!` macro is that it can increase the
84 //! size of your program's binary since it generates specialized Rust code.
85 //! The extra size probably won't be significant for a small number of
86 //! expressions, but 100+ calls to `regex!` will probably result in a
87 //! noticeably bigger binary.
88 //!
89 //! # Example: iterating over capture groups
90 //!
91 //! This crate provides convenient iterators for matching an expression
92 //! repeatedly against a search string to find successive non-overlapping
93 //! matches. For example, to find all dates in a string and be able to access
94 //! them by their component pieces:
95 //!
96 //! ```rust
97 //! # #![feature(phase)]
98 //! # extern crate regex; #[phase(plugin)] extern crate regex_macros;
99 //! # fn main() {
100 //! let re = regex!(r"(\d{4})-(\d{2})-(\d{2})");
101 //! let text = "2012-03-14, 2013-01-01 and 2014-07-05";
102 //! for cap in re.captures_iter(text) {
103 //!     println!("Month: {} Day: {} Year: {}", cap.at(2), cap.at(3), cap.at(1));
104 //! }
105 //! // Output:
106 //! // Month: 03 Day: 14 Year: 2012
107 //! // Month: 01 Day: 01 Year: 2013
108 //! // Month: 07 Day: 05 Year: 2014
109 //! # }
110 //! ```
111 //!
112 //! Notice that the year is in the capture group indexed at `1`. This is
113 //! because the *entire match* is stored in the capture group at index `0`.
114 //!
115 //! # Example: replacement with named capture groups
116 //!
117 //! Building on the previous example, perhaps we'd like to rearrange the date
118 //! formats. This can be done with text replacement. But to make the code
119 //! clearer, we can *name*  our capture groups and use those names as variables
120 //! in our replacement text:
121 //!
122 //! ```rust
123 //! # #![feature(phase)]
124 //! # extern crate regex; #[phase(plugin)] extern crate regex_macros;
125 //! # fn main() {
126 //! let re = regex!(r"(?P<y>\d{4})-(?P<m>\d{2})-(?P<d>\d{2})");
127 //! let before = "2012-03-14, 2013-01-01 and 2014-07-05";
128 //! let after = re.replace_all(before, "$m/$d/$y");
129 //! assert_eq!(after.as_slice(), "03/14/2012, 01/01/2013 and 07/05/2014");
130 //! # }
131 //! ```
132 //!
133 //! The `replace` methods are actually polymorphic in the replacement, which
134 //! provides more flexibility than is seen here. (See the documentation for
135 //! `Regex::replace` for more details.)
136 //!
137 //! # Pay for what you use
138 //!
139 //! With respect to searching text with a regular expression, there are three
140 //! questions that can be asked:
141 //!
142 //! 1. Does the text match this expression?
143 //! 2. If so, where does it match?
144 //! 3. Where are the submatches?
145 //!
146 //! Generally speaking, this crate could provide a function to answer only #3,
147 //! which would subsume #1 and #2 automatically. However, it can be
148 //! significantly more expensive to compute the location of submatches, so it's
149 //! best not to do it if you don't need to.
150 //!
151 //! Therefore, only use what you need. For example, don't use `find` if you
152 //! only need to test if an expression matches a string. (Use `is_match`
153 //! instead.)
154 //!
155 //! # Unicode
156 //!
157 //! This implementation executes regular expressions **only** on sequences of
158 //! Unicode code points while exposing match locations as byte indices into the
159 //! search string.
160 //!
161 //! Currently, only naive case folding is supported. Namely, when matching
162 //! case insensitively, the characters are first converted to their uppercase
163 //! forms and then compared.
164 //!
165 //! Regular expressions themselves are also **only** interpreted as a sequence
166 //! of Unicode code points. This means you can use Unicode characters
167 //! directly in your expression:
168 //!
169 //! ```rust
170 //! # #![feature(phase)]
171 //! # extern crate regex; #[phase(plugin)] extern crate regex_macros;
172 //! # fn main() {
173 //! let re = regex!(r"(?i)Δ+");
174 //! assert_eq!(re.find("ΔδΔ"), Some((0, 6)));
175 //! # }
176 //! ```
177 //!
178 //! Finally, Unicode general categories and scripts are available as character
179 //! classes. For example, you can match a sequence of numerals, Greek or
180 //! Cherokee letters:
181 //!
182 //! ```rust
183 //! # #![feature(phase)]
184 //! # extern crate regex; #[phase(plugin)] extern crate regex_macros;
185 //! # fn main() {
186 //! let re = regex!(r"[\pN\p{Greek}\p{Cherokee}]+");
187 //! assert_eq!(re.find("abcΔᎠβⅠᏴγδⅡxyz"), Some((3, 23)));
188 //! # }
189 //! ```
190 //!
191 //! # Syntax
192 //!
193 //! The syntax supported in this crate is almost in an exact correspondence
194 //! with the syntax supported by RE2.
195 //!
196 //! ## Matching one character
197 //!
198 //! <pre class="rust">
199 //! .           any character except new line (includes new line with s flag)
200 //! [xyz]       A character class matching either x, y or z.
201 //! [^xyz]      A character class matching any character except x, y and z.
202 //! [a-z]       A character class matching any character in range a-z.
203 //! \d          Perl character class ([0-9])
204 //! \D          Negated Perl character class ([^0-9])
205 //! [:alpha:]   ASCII character class ([A-Za-z])
206 //! [:^alpha:]  Negated ASCII character class ([^A-Za-z])
207 //! \pN         One letter name Unicode character class
208 //! \p{Greek}   Unicode character class (general category or script)
209 //! \PN         Negated one letter name Unicode character class
210 //! \P{Greek}   negated Unicode character class (general category or script)
211 //! </pre>
212 //!
213 //! Any named character class may appear inside a bracketed `[...]` character
214 //! class. For example, `[\p{Greek}\pN]` matches any Greek or numeral
215 //! character.
216 //!
217 //! ## Composites
218 //!
219 //! <pre class="rust">
220 //! xy    concatenation (x followed by y)
221 //! x|y   alternation (x or y, prefer x)
222 //! </pre>
223 //!
224 //! ## Repetitions
225 //!
226 //! <pre class="rust">
227 //! x*        zero or more of x (greedy)
228 //! x+        one or more of x (greedy)
229 //! x?        zero or one of x (greedy)
230 //! x*?       zero or more of x (ungreedy)
231 //! x+?       one or more of x (ungreedy)
232 //! x??       zero or one of x (ungreedy)
233 //! x{n,m}    at least n x and at most m x (greedy)
234 //! x{n,}     at least n x (greedy)
235 //! x{n}      exactly n x
236 //! x{n,m}?   at least n x and at most m x (ungreedy)
237 //! x{n,}?    at least n x (ungreedy)
238 //! x{n}?     exactly n x
239 //! </pre>
240 //!
241 //! ## Empty matches
242 //!
243 //! <pre class="rust">
244 //! ^     the beginning of text (or start-of-line with multi-line mode)
245 //! $     the end of text (or end-of-line with multi-line mode)
246 //! \A    only the beginning of text (even with multi-line mode enabled)
247 //! \z    only the end of text (even with multi-line mode enabled)
248 //! \b    a Unicode word boundary (\w on one side and \W, \A, or \z on other)
249 //! \B    not a Unicode word boundary
250 //! </pre>
251 //!
252 //! ## Grouping and flags
253 //!
254 //! <pre class="rust">
255 //! (exp)          numbered capture group (indexed by opening parenthesis)
256 //! (?P&lt;name&gt;exp)  named (also numbered) capture group (allowed chars: [_0-9a-zA-Z])
257 //! (?:exp)        non-capturing group
258 //! (?flags)       set flags within current group
259 //! (?flags:exp)   set flags for exp (non-capturing)
260 //! </pre>
261 //!
262 //! Flags are each a single character. For example, `(?x)` sets the flag `x`
263 //! and `(?-x)` clears the flag `x`. Multiple flags can be set or cleared at
264 //! the same time: `(?xy)` sets both the `x` and `y` flags and `(?x-y)` sets
265 //! the `x` flag and clears the `y` flag.
266 //!
267 //! All flags are by default disabled. They are:
268 //!
269 //! <pre class="rust">
270 //! i     case insensitive
271 //! m     multi-line mode: ^ and $ match begin/end of line
272 //! s     allow . to match \n
273 //! U     swap the meaning of x* and x*?
274 //! </pre>
275 //!
276 //! Here's an example that matches case insensitively for only part of the
277 //! expression:
278 //!
279 //! ```rust
280 //! # #![feature(phase)]
281 //! # extern crate regex; #[phase(plugin)] extern crate regex_macros;
282 //! # fn main() {
283 //! let re = regex!(r"(?i)a+(?-i)b+");
284 //! let cap = re.captures("AaAaAbbBBBb").unwrap();
285 //! assert_eq!(cap.at(0), "AaAaAbb");
286 //! # }
287 //! ```
288 //!
289 //! Notice that the `a+` matches either `a` or `A`, but the `b+` only matches
290 //! `b`.
291 //!
292 //! ## Escape sequences
293 //!
294 //! <pre class="rust">
295 //! \*         literal *, works for any punctuation character: \.+*?()|[]{}^$
296 //! \a         bell (\x07)
297 //! \f         form feed (\x0C)
298 //! \t         horizontal tab
299 //! \n         new line
300 //! \r         carriage return
301 //! \v         vertical tab (\x0B)
302 //! \123       octal character code (up to three digits)
303 //! \x7F       hex character code (exactly two digits)
304 //! \x{10FFFF} any hex character code corresponding to a Unicode code point
305 //! </pre>
306 //!
307 //! ## Perl character classes (Unicode friendly)
308 //!
309 //! <pre class="rust">
310 //! \d     digit ([0-9] + \p{Nd})
311 //! \D     not digit
312 //! \s     whitespace ([\t\n\f\r ] + \p{Z})
313 //! \S     not whitespace
314 //! \w     word character ([0-9A-Za-z_] + \p{L})
315 //! \W     not word character
316 //! </pre>
317 //!
318 //! ## ASCII character classes
319 //!
320 //! <pre class="rust">
321 //! [:alnum:]    alphanumeric ([0-9A-Za-z])
322 //! [:alpha:]    alphabetic ([A-Za-z])
323 //! [:ascii:]    ASCII ([\x00-\x7F])
324 //! [:blank:]    blank ([\t ])
325 //! [:cntrl:]    control ([\x00-\x1F\x7F])
326 //! [:digit:]    digits ([0-9])
327 //! [:graph:]    graphical ([!-~])
328 //! [:lower:]    lower case ([a-z])
329 //! [:print:]    printable ([ -~])
330 //! [:punct:]    punctuation ([!-/:-@[-`{-~])
331 //! [:space:]    whitespace ([\t\n\v\f\r ])
332 //! [:upper:]    upper case ([A-Z])
333 //! [:word:]     word characters ([0-9A-Za-z_])
334 //! [:xdigit:]   hex digit ([0-9A-Fa-f])
335 //! </pre>
336 //!
337 //! # Untrusted input
338 //!
339 //! There are two factors to consider here: untrusted regular expressions and
340 //! untrusted search text.
341 //!
342 //! Currently, there are no counter-measures in place to prevent a malicious
343 //! user from writing an expression that may use a lot of resources. One such
344 //! example is to repeat counted repetitions: `((a{100}){100}){100}` will try
345 //! to repeat the `a` instruction `100^3` times. Essentially, this means it's
346 //! very easy for an attacker to exhaust your system's memory if they are
347 //! allowed to execute arbitrary regular expressions. A possible solution to
348 //! this is to impose a hard limit on the size of a compiled expression, but it
349 //! does not yet exist.
350 //!
351 //! The story is a bit better with untrusted search text, since this crate's
352 //! implementation provides `O(nm)` search where `n` is the number of
353 //! characters in the search text and `m` is the number of instructions in a
354 //! compiled expression.
355
356 #![crate_id = "regex#0.11.0"]
357 #![crate_type = "rlib"]
358 #![crate_type = "dylib"]
359 #![experimental]
360 #![license = "MIT/ASL2"]
361 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
362        html_favicon_url = "http://www.rust-lang.org/favicon.ico",
363        html_root_url = "http://doc.rust-lang.org/0.11.0/",
364        html_playground_url = "http://play.rust-lang.org/")]
365
366 #![feature(macro_rules, phase)]
367 #![deny(missing_doc)]
368
369 #[cfg(test)]
370 extern crate stdtest = "test";
371 #[cfg(test)]
372 extern crate rand;
373
374 // During tests, this links with the `regex` crate so that the `regex!` macro
375 // can be tested.
376 #[cfg(test)]
377 extern crate regex;
378
379 pub use parse::Error;
380 pub use re::{Regex, Captures, SubCaptures, SubCapturesPos};
381 pub use re::{FindCaptures, FindMatches};
382 pub use re::{Replacer, NoExpand, RegexSplits, RegexSplitsN};
383 pub use re::{quote, is_match};
384
385 mod compile;
386 mod parse;
387 mod re;
388 mod vm;
389
390 // FIXME(#13725) windows needs fixing.
391 #[cfg(test, not(windows))]
392 mod test;
393
394 /// The `native` module exists to support the `regex!` macro. Do not use.
395 #[doc(hidden)]
396 pub mod native {
397     // Exporting this stuff is bad form, but it's necessary for two reasons.
398     // Firstly, the `regex!` syntax extension is in a different crate and
399     // requires access to the representation of a regex (particularly the
400     // instruction set) in order to compile to native Rust. This could be
401     // mitigated if `regex!` was defined in the same crate, but this has
402     // undesirable consequences (such as requiring a dependency on
403     // `libsyntax`).
404     //
405     // Secondly, the code generated by `regex!` must *also* be able
406     // to access various functions in this crate to reduce code duplication
407     // and to provide a value with precisely the same `Regex` type in this
408     // crate. This, AFAIK, is impossible to mitigate.
409     //
410     // On the bright side, `rustdoc` lets us hide this from the public API
411     // documentation.
412     pub use compile::{
413         Program,
414         OneChar, CharClass, Any, Save, Jump, Split,
415         Match, EmptyBegin, EmptyEnd, EmptyWordBoundary,
416     };
417     pub use parse::{
418         FLAG_EMPTY, FLAG_NOCASE, FLAG_MULTI, FLAG_DOTNL,
419         FLAG_SWAP_GREED, FLAG_NEGATED,
420     };
421     pub use re::{Dynamic, Native};
422     pub use vm::{
423         MatchKind, Exists, Location, Submatches,
424         StepState, StepMatchEarlyReturn, StepMatch, StepContinue,
425         CharReader, find_prefix,
426     };
427 }