Struct Regex
pub struct Regex { /* private fields */ }
A compiled regular expression for searching Unicode haystacks.
A Regex can be used to search haystacks, split haystacks into substrings
or replace substrings in a haystack with a different substring. All
searching is done with an implicit (?s:.)*? at the beginning and end of
an pattern. To force an expression to match the whole string (or a prefix
or a suffix), you must use an anchor like ^ or $ (or \A and \z).
Like the Regex type in the parent module, matches with this regex return
byte offsets into the haystack. Unlike the parent Regex type, these
byte offsets may not correspond to UTF-8 sequence boundaries since the
regexes in this module can match arbitrary bytes.
The only methods that allocate new byte strings are the string replacement methods. All other methods (searching and splitting) return borrowed references into the haystack given.
Example
Find the offsets of a US phone number:
use Regex;
let re = new.unwrap;
let m = re.find.unwrap;
assert_eq!;
Example: extracting capture groups
A common way to use regexes is with capture groups. That is, instead of just looking for matches of an entire regex, parentheses are used to create groups that represent part of the match.
For example, consider a haystack with multiple lines, and each line has
three whitespace delimited fields where the second field is expected to be
a number and the third field a boolean. To make this convenient, we use
the Captures::extract API to put the strings that match each group
into a fixed size array:
use Regex;
let hay = b"
rabbit 54 true
groundhog 2 true
does not match
fox 109 false
";
let re = new.unwrap;
let mut fields: = vec!;
for in re.captures_iter.map
assert_eq!;
# Ok::
Example: matching invalid UTF-8
One of the reasons for searching &[u8] haystacks is that the &[u8]
might not be valid UTF-8. Indeed, with a bytes::Regex, patterns that
match invalid UTF-8 are explicitly allowed. Here's one example that looks
for valid UTF-8 fields that might be separated by invalid UTF-8. In this
case, we use (?s-u:.), which matches any byte. Attempting to use it in a
top-level Regex will result in the regex failing to compile. Notice also
that we use . with Unicode mode enabled, in which case, only valid UTF-8
is matched. In this way, we can build one pattern where some parts only
match valid UTF-8 while other parts are more permissive.
use Regex;
// F0 9F 92 A9 is the UTF-8 encoding for a Pile of Poo.
let hay = b"\xFF\xFFfoo\xFF\xFF\xFF\xF0\x9F\x92\xA9\xFF";
// An equivalent to '(?s-u:.)' is '(?-u:[\x00-\xFF])'.
let re = new.unwrap;
let caps = re.captures.unwrap;
assert_eq!;
assert_eq!;
Implementations
impl Regex
fn as_str(&self) -> &strReturns the original string of this regex.
Example
use Regex; let re = new.unwrap; assert_eq!;fn capture_names(&self) -> CaptureNames<'_>Returns an iterator over the capture names in this regex.
The iterator returned yields elements of type
Option<&str>. That is, the iterator yields values for all capture groups, even ones that are unnamed. The order of the groups corresponds to the order of the group's corresponding opening parenthesis.The first element of the iterator always yields the group corresponding to the overall match, and this group is always unnamed. Therefore, the iterator always yields at least one group.
Example
This shows basic usage with a mix of named and unnamed capture groups:
use Regex; let re = new.unwrap; let mut names = re.capture_names; assert_eq!; assert_eq!; assert_eq!; assert_eq!; // the '(?:.)' group is non-capturing and so doesn't appear here! assert_eq!; assert_eq!;The iterator always yields at least one element, even for regexes with no capture groups and even for regexes that can never match:
use Regex; let re = new.unwrap; let mut names = re.capture_names; assert_eq!; assert_eq!; let re = new.unwrap; let mut names = re.capture_names; assert_eq!; assert_eq!;fn captures_len(&self) -> usizeReturns the number of captures groups in this regex.
This includes all named and unnamed groups, including the implicit unnamed group that is always present and corresponds to the entire match.
Since the implicit unnamed group is always included in this length, the length returned is guaranteed to be greater than zero.
Example
use Regex; let re = new.unwrap; assert_eq!; let re = new.unwrap; assert_eq!; let re = new.unwrap; assert_eq!; let re = new.unwrap; assert_eq!;fn static_captures_len(&self) -> Option<usize>Returns the total number of capturing groups that appear in every possible match.
If the number of capture groups can vary depending on the match, then this returns
None. That is, a value is only returned when the number of matching groups is invariant or "static."Note that like
Regex::captures_len, this does include the implicit capturing group corresponding to the entire match. Therefore, when a non-None value is returned, it is guaranteed to be at least1. Stated differently, a return value ofSome(0)is impossible.Example
This shows a few cases where a static number of capture groups is available and a few cases where it is not.
use Regex; let len = ; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!; # Ok::fn capture_locations(&self) -> CaptureLocationsReturns a fresh allocated set of capture locations that can be reused in multiple calls to
Regex::captures_readorRegex::captures_read_at.Example
use Regex; let re = new.unwrap; let mut locs = re.capture_locations; assert!; assert_eq!; assert_eq!; assert_eq!; assert_eq!;
impl Regex
fn new(re: &str) -> Result<Regex, Error>Compiles a regular expression. Once compiled, it can be used repeatedly to search, split or replace substrings in a haystack.
Note that regex compilation tends to be a somewhat expensive process, and unlike higher level environments, compilation is not automatically cached for you. One should endeavor to compile a regex once and then reuse it. For example, it's a bad idea to compile the same regex repeatedly in a loop.
Errors
If an invalid pattern is given, then an error is returned. An error is also returned if the pattern is valid, but would produce a regex that is bigger than the configured size limit via
RegexBuilder::size_limit. (A reasonable size limit is enabled by default.)Example
use Regex; // An Invalid pattern because of an unclosed parenthesis assert!; // An invalid pattern because the regex would be too big // because Unicode tends to inflate things. assert!; // Disabling Unicode can make the regex much smaller, // potentially by up to or more than an order of magnitude. assert!;fn is_match(&self, haystack: &[u8]) -> boolReturns true if and only if there is a match for the regex anywhere in the haystack given.
It is recommended to use this method if all you need to do is test whether a match exists, since the underlying matching engine may be able to do less work.
Example
Test if some haystack contains at least one word with exactly 13 Unicode word characters:
use Regex; let re = new.unwrap; let hay = b"I categorically deny having triskaidekaphobia."; assert!;fn find<'h>(&self, haystack: &'h [u8]) -> Option<Match<'h>>This routine searches for the first match of this regex in the haystack given, and if found, returns a
Match. TheMatchprovides access to both the byte offsets of the match and the actual substring that matched.Note that this should only be used if you want to find the entire match. If instead you just want to test the existence of a match, it's potentially faster to use
Regex::is_match(hay)instead ofRegex::find(hay).is_some().Example
Find the first word with exactly 13 Unicode word characters:
use Regex; let re = new.unwrap; let hay = b"I categorically deny having triskaidekaphobia."; let mat = re.find.unwrap; assert_eq!; assert_eq!;fn find_iter<'r, 'h>(&'r self, haystack: &'h [u8]) -> Matches<'r, 'h>Returns an iterator that yields successive non-overlapping matches in the given haystack. The iterator yields values of type
Match.Time complexity
Note that since
find_iterruns potentially many searches on the haystack and since each search has worst caseO(m * n)time complexity, the overall worst case time complexity for iteration isO(m * n^2).Example
Find every word with exactly 13 Unicode word characters:
use Regex; let re = new.unwrap; let hay = b"Retroactively relinquishing remunerations is reprehensible."; let matches: = re.find_iter.map.collect; assert_eq!;fn captures<'h>(&self, haystack: &'h [u8]) -> Option<Captures<'h>>This routine searches for the first match of this regex in the haystack given, and if found, returns not only the overall match but also the matches of each capture group in the regex. If no match is found, then
Noneis returned.Capture group
0always corresponds to an implicit unnamed group that includes the entire match. If a match is found, this group is always present. Subsequent groups may be named and are numbered, starting at 1, by the order in which the opening parenthesis appears in the pattern. For example, in the pattern(?<a>.(?<b>.))(?<c>.),a,bandccorrespond to capture group indices1,2and3, respectively.You should only use
capturesif you need access to the capture group matches. Otherwise,Regex::findis generally faster for discovering just the overall match.Example
Say you have some haystack with movie names and their release years, like "'Citizen Kane' (1941)". It'd be nice if we could search for strings looking like that, while also extracting the movie name and its release year separately. The example below shows how to do that.
use Regex; let re = new.unwrap; let hay = b"Not my favorite movie: 'Citizen Kane' (1941)."; let caps = re.captures.unwrap; assert_eq!; assert_eq!; assert_eq!; // You can also access the groups by index using the Index notation. // Note that this will panic on an invalid index. In this case, these // accesses are always correct because the overall regex will only // match when these capture groups match. assert_eq!; assert_eq!; assert_eq!;Note that the full match is at capture group
0. Each subsequent capture group is indexed by the order of its opening(.We can make this example a bit clearer by using named capture groups:
use Regex; let re = new.unwrap; let hay = b"Not my favorite movie: 'Citizen Kane' (1941)."; let caps = re.captures.unwrap; assert_eq!; assert_eq!; assert_eq!; // You can also access the groups by name using the Index notation. // Note that this will panic on an invalid group name. In this case, // these accesses are always correct because the overall regex will // only match when these capture groups match. assert_eq!; assert_eq!; assert_eq!;Here we name the capture groups, which we can access with the
namemethod or theIndexnotation with a&str. Note that the named capture groups are still accessible withgetor theIndexnotation with ausize.The
0th capture group is always unnamed, so it must always be accessed withget(0)or[0].Finally, one other way to get the matched substrings is with the
Captures::extractAPI:use Regex; let re = new.unwrap; let hay = b"Not my favorite movie: 'Citizen Kane' (1941)."; let = re.captures.unwrap.extract; assert_eq!; assert_eq!; assert_eq!;fn captures_iter<'r, 'h>(&'r self, haystack: &'h [u8]) -> CaptureMatches<'r, 'h>Returns an iterator that yields successive non-overlapping matches in the given haystack. The iterator yields values of type
Captures.This is the same as
Regex::find_iter, but instead of only providing access to the overall match, each value yield includes access to the matches of all capture groups in the regex. Reporting this extra match data is potentially costly, so callers should only usecaptures_iteroverfind_iterwhen they actually need access to the capture group matches.Time complexity
Note that since
captures_iterruns potentially many searches on the haystack and since each search has worst caseO(m * n)time complexity, the overall worst case time complexity for iteration isO(m * n^2).Example
We can use this to find all movie titles and their release years in some haystack, where the movie is formatted like "'Title' (xxxx)":
use Regex; let re = new.unwrap; let hay = b"'Citizen Kane' (1941), 'The Wizard of Oz' (1939), 'M' (1931)."; let mut movies = vec!; for in re.captures_iter.map assert_eq!; # Ok::Or with named groups:
use Regex; let re = new.unwrap; let hay = b"'Citizen Kane' (1941), 'The Wizard of Oz' (1939), 'M' (1931)."; let mut it = re.captures_iter; let caps = it.next.unwrap; assert_eq!; assert_eq!; let caps = it.next.unwrap; assert_eq!; assert_eq!; let caps = it.next.unwrap; assert_eq!; assert_eq!;fn split<'r, 'h>(&'r self, haystack: &'h [u8]) -> Split<'r, 'h>Returns an iterator of substrings of the haystack given, delimited by a match of the regex. Namely, each element of the iterator corresponds to a part of the haystack that isn't matched by the regular expression.
Time complexity
Since iterators over all matches requires running potentially many searches on the haystack, and since each search has worst case
O(m * n)time complexity, the overall worst case time complexity for this routine isO(m * n^2).Example
To split a string delimited by arbitrary amounts of spaces or tabs:
use Regex; let re = new.unwrap; let hay = b"a b \t c\td e"; let fields: = re.split.collect; assert_eq!;Example: more cases
Basic usage:
use Regex; let re = new.unwrap; let hay = b"Mary had a little lamb"; let got: = re.split.collect; assert_eq!; let re = new.unwrap; let hay = b""; let got: = re.split.collect; assert_eq!; let re = new.unwrap; let hay = b"lionXXtigerXleopard"; let got: = re.split.collect; assert_eq!; let re = new.unwrap; let hay = b"lion::tiger::leopard"; let got: = re.split.collect; assert_eq!;If a haystack contains multiple contiguous matches, you will end up with empty spans yielded by the iterator:
use Regex; let re = new.unwrap; let hay = b"XXXXaXXbXc"; let got: = re.split.collect; assert_eq!; let re = new.unwrap; let hay = b"(///)"; let got: = re.split.collect; assert_eq!;Separators at the start or end of a haystack are neighbored by empty substring.
use Regex; let re = new.unwrap; let hay = b"010"; let got: = re.split.collect; assert_eq!;When the regex can match the empty string, it splits at every byte position in the haystack. This includes between all UTF-8 code units. (The top-level
Regex::splitwill only split at valid UTF-8 boundaries.)use Regex; let re = new.unwrap; let hay = "☃".as_bytes; let got: = re.split.collect; assert_eq!;Contiguous separators (commonly shows up with whitespace), can lead to possibly surprising behavior. For example, this code is correct:
use Regex; let re = new.unwrap; let hay = b" a b c"; let got: = re.split.collect; assert_eq!;It does not give you
["a", "b", "c"]. For that behavior, you'd want to match contiguous space characters:use Regex; let re = new.unwrap; let hay = b" a b c"; let got: = re.split.collect; // N.B. This does still include a leading empty span because ' +' // matches at the beginning of the haystack. assert_eq!;fn splitn<'r, 'h>(&'r self, haystack: &'h [u8], limit: usize) -> SplitN<'r, 'h>Returns an iterator of at most
limitsubstrings of the haystack given, delimited by a match of the regex. (Alimitof0will return no substrings.) Namely, each element of the iterator corresponds to a part of the haystack that isn't matched by the regular expression. The remainder of the haystack that is not split will be the last element in the iterator.Time complexity
Since iterators over all matches requires running potentially many searches on the haystack, and since each search has worst case
O(m * n)time complexity, the overall worst case time complexity for this routine isO(m * n^2).Although note that the worst case time here has an upper bound given by the
limitparameter.Example
Get the first two words in some haystack:
use Regex; let re = new.unwrap; let hay = b"Hey! How are you?"; let fields: = re.splitn.collect; assert_eq!;Examples: more cases
use Regex; let re = new.unwrap; let hay = b"Mary had a little lamb"; let got: = re.splitn.collect; assert_eq!; let re = new.unwrap; let hay = b""; let got: = re.splitn.collect; assert_eq!; let re = new.unwrap; let hay = b"lionXXtigerXleopard"; let got: = re.splitn.collect; assert_eq!; let re = new.unwrap; let hay = b"lion::tiger::leopard"; let got: = re.splitn.collect; assert_eq!; let re = new.unwrap; let hay = b"abcXdef"; let got: = re.splitn.collect; assert_eq!; let re = new.unwrap; let hay = b"abcdef"; let got: = re.splitn.collect; assert_eq!; let re = new.unwrap; let hay = b"abcXdef"; let got: = re.splitn.collect; assert!;fn replace<'h, R: Replacer>(&self, haystack: &'h [u8], rep: R) -> Cow<'h, [u8]>Replaces the leftmost-first match in the given haystack with the replacement provided. The replacement can be a regular string (where
$Nand$nameare expanded to match capture groups) or a function that takes aCapturesand returns the replaced string.If no match is found, then the haystack is returned unchanged. In that case, this implementation will likely return a
Cow::Borrowedvalue such that no allocation is performed.When a
Cow::Borrowedis returned, the value returned is guaranteed to be equivalent to thehaystackgiven.Replacement string syntax
All instances of
$refin the replacement string are replaced with the substring corresponding to the capture group identified byref.refmay be an integer corresponding to the index of the capture group (counted by order of opening parenthesis where0is the entire match) or it can be a name (consisting of letters, digits or underscores) corresponding to a named capture group.If
refisn't a valid capture group (whether the name doesn't exist or isn't a valid index), then it is replaced with the empty string.The longest possible name is used. For example,
$1alooks up the capture group named1aand not the capture group at index1. To exert more precise control over the name, use braces, e.g.,${1}a.To write a literal
$use$$.Example
Note that this function is polymorphic with respect to the replacement. In typical usage, this can just be a normal string:
use Regex; let re = new.unwrap; assert_eq!;But anything satisfying the
Replacertrait will work. For example, a closure of type|&Captures| -> Stringprovides direct access to the captures corresponding to a match. This allows one to access capturing group matches easily:use ; let re = new.unwrap; let result = re.replace; assert_eq!;But this is a bit cumbersome to use all the time. Instead, a simple syntax is supported (as described above) that expands
$nameinto the corresponding capture group. Here's the last example, but using this expansion technique with named capture groups:use Regex; let re = new.unwrap; let result = re.replace; assert_eq!;Note that using
$2instead of$firstor$1instead of$lastwould produce the same result. To write a literal$use$$.Sometimes the replacement string requires use of curly braces to delineate a capture group replacement when it is adjacent to some other literal text. For example, if we wanted to join two words together with an underscore:
use Regex; let re = new.unwrap; let result = re.replace; assert_eq!;Without the curly braces, the capture group name
first_would be used, and since it doesn't exist, it would be replaced with the empty string.Finally, sometimes you just want to replace a literal string with no regard for capturing group expansion. This can be done by wrapping a string with [
NoExpand]:use ; let re = new.unwrap; let result = re.replace; assert_eq!;Using
NoExpandmay also be faster, since the replacement string won't need to be parsed for the$syntax.fn replace_all<'h, R: Replacer>(&self, haystack: &'h [u8], rep: R) -> Cow<'h, [u8]>Replaces all non-overlapping matches in the haystack with the replacement provided. This is the same as calling
replacenwithlimitset to0.If no match is found, then the haystack is returned unchanged. In that case, this implementation will likely return a
Cow::Borrowedvalue such that no allocation is performed.When a
Cow::Borrowedis returned, the value returned is guaranteed to be equivalent to thehaystackgiven.The documentation for
Regex::replacegoes into more detail about what kinds of replacement strings are supported.Time complexity
Since iterators over all matches requires running potentially many searches on the haystack, and since each search has worst case
O(m * n)time complexity, the overall worst case time complexity for this routine isO(m * n^2).Fallibility
If you need to write a replacement routine where any individual replacement might "fail," doing so with this API isn't really feasible because there's no way to stop the search process if a replacement fails. Instead, if you need this functionality, you should consider implementing your own replacement routine:
use ; // Let's replace each word with the number of bytes in that word. // But if we see a word that is "too long," we'll give up. let re = new.unwrap; let replacement = ; assert_eq!; assert!;Example
This example shows how to flip the order of whitespace (excluding line terminators) delimited fields, and normalizes the whitespace that delimits the fields:
use Regex; let re = new.unwrap; let hay = b" Greetings 1973 Wild\t1973 BornToRun\t\t\t\t1975 Darkness 1978 TheRiver 1980 "; let new = re.replace_all; assert_eq!;fn replacen<'h, R: Replacer>(&self, haystack: &'h [u8], limit: usize, rep: R) -> Cow<'h, [u8]>Replaces at most
limitnon-overlapping matches in the haystack with the replacement provided. Iflimitis0, then all non-overlapping matches are replaced. That is,Regex::replace_all(hay, rep)is equivalent toRegex::replacen(hay, 0, rep).If no match is found, then the haystack is returned unchanged. In that case, this implementation will likely return a
Cow::Borrowedvalue such that no allocation is performed.When a
Cow::Borrowedis returned, the value returned is guaranteed to be equivalent to thehaystackgiven.The documentation for
Regex::replacegoes into more detail about what kinds of replacement strings are supported.Time complexity
Since iterators over all matches requires running potentially many searches on the haystack, and since each search has worst case
O(m * n)time complexity, the overall worst case time complexity for this routine isO(m * n^2).Although note that the worst case time here has an upper bound given by the
limitparameter.Fallibility
See the corresponding section in the docs for
Regex::replace_allfor tips on how to deal with a replacement routine that can fail.Example
This example shows how to flip the order of whitespace (excluding line terminators) delimited fields, and normalizes the whitespace that delimits the fields. But we only do it for the first two matches.
use Regex; let re = new.unwrap; let hay = b" Greetings 1973 Wild\t1973 BornToRun\t\t\t\t1975 Darkness 1978 TheRiver 1980 "; let new = re.replacen; assert_eq!;
impl Regex
fn shortest_match(&self, haystack: &[u8]) -> Option<usize>Returns the end byte offset of the first match in the haystack given.
This method may have the same performance characteristics as
is_match. Behaviorally, it doesn't just report whether it match occurs, but also the end offset for a match. In particular, the offset returned may be shorter than the proper end of the leftmost-first match that you would find viaRegex::find.Note that it is not guaranteed that this routine finds the shortest or "earliest" possible match. Instead, the main idea of this API is that it returns the offset at the point at which the internal regex engine has determined that a match has occurred. This may vary depending on which internal regex engine is used, and thus, the offset itself may change based on internal heuristics.
Example
Typically,
a+would match the entire first sequence ofain some haystack, butshortest_matchmay give up as soon as it sees the firsta.use Regex; let re = new.unwrap; let offset = re.shortest_match.unwrap; assert_eq!;fn shortest_match_at(&self, haystack: &[u8], start: usize) -> Option<usize>Returns the same as
shortest_match, but starts the search at the given offset.The significance of the starting point is that it takes the surrounding context into consideration. For example, the
\Aanchor can only match whenstart == 0.If a match is found, the offset returned is relative to the beginning of the haystack, not the beginning of the search.
Panics
This panics when
start >= haystack.len() + 1.Example
This example shows the significance of
startby demonstrating how it can be used to permit look-around assertions in a regex to take the surrounding context into account.use Regex; let re = new.unwrap; let hay = b"eschew"; // We get a match here, but it's probably not intended. assert_eq!; // No match because the assertions take the context into account. assert_eq!;fn is_match_at(&self, haystack: &[u8], start: usize) -> boolReturns the same as
Regex::is_match, but starts the search at the given offset.The significance of the starting point is that it takes the surrounding context into consideration. For example, the
\Aanchor can only match whenstart == 0.Panics
This panics when
start >= haystack.len() + 1.Example
This example shows the significance of
startby demonstrating how it can be used to permit look-around assertions in a regex to take the surrounding context into account.use Regex; let re = new.unwrap; let hay = b"eschew"; // We get a match here, but it's probably not intended. assert!; // No match because the assertions take the context into account. assert!;fn find_at<'h>(&self, haystack: &'h [u8], start: usize) -> Option<Match<'h>>Returns the same as
Regex::find, but starts the search at the given offset.The significance of the starting point is that it takes the surrounding context into consideration. For example, the
\Aanchor can only match whenstart == 0.Panics
This panics when
start >= haystack.len() + 1.Example
This example shows the significance of
startby demonstrating how it can be used to permit look-around assertions in a regex to take the surrounding context into account.use Regex; let re = new.unwrap; let hay = b"eschew"; // We get a match here, but it's probably not intended. assert_eq!; // No match because the assertions take the context into account. assert_eq!;fn captures_at<'h>(&self, haystack: &'h [u8], start: usize) -> Option<Captures<'h>>Returns the same as
Regex::captures, but starts the search at the given offset.The significance of the starting point is that it takes the surrounding context into consideration. For example, the
\Aanchor can only match whenstart == 0.Panics
This panics when
start >= haystack.len() + 1.Example
This example shows the significance of
startby demonstrating how it can be used to permit look-around assertions in a regex to take the surrounding context into account.use Regex; let re = new.unwrap; let hay = b"eschew"; // We get a match here, but it's probably not intended. assert_eq!; // No match because the assertions take the context into account. assert!;fn captures_read<'h>(&self, locs: &mut CaptureLocations, haystack: &'h [u8]) -> Option<Match<'h>>This is like
Regex::captures, but writes the byte offsets of each capture group match into the locations given.A
CaptureLocationsstores the same byte offsets as aCaptures, but does not store a reference to the haystack. This makes its API a bit lower level and less convenient. But in exchange, callers may allocate their ownCaptureLocationsand reuse it for multiple searches. This may be helpful if allocating aCapturesshows up in a profile as too costly.To create a
CaptureLocationsvalue, use theRegex::capture_locationsmethod.This also returns the overall match if one was found. When a match is found, its offsets are also always stored in
locsat index0.Example
use Regex; let re = new.unwrap; let mut locs = re.capture_locations; assert!; assert_eq!; assert_eq!; assert_eq!;fn captures_read_at<'h>(&self, locs: &mut CaptureLocations, haystack: &'h [u8], start: usize) -> Option<Match<'h>>Returns the same as
Regex::captures_read, but starts the search at the given offset.The significance of the starting point is that it takes the surrounding context into consideration. For example, the
\Aanchor can only match whenstart == 0.Panics
This panics when
start >= haystack.len() + 1.Example
This example shows the significance of
startby demonstrating how it can be used to permit look-around assertions in a regex to take the surrounding context into account.use Regex; let re = new.unwrap; let hay = b"eschew"; let mut locs = re.capture_locations; // We get a match here, but it's probably not intended. assert!; // No match because the assertions take the context into account. assert!;
Trait Implementations
impl Clone for Regex
fn clone(&self) -> Self
impl Debug for Regex
fn fmt(&self, f: &mut Formatter<'_>) -> ResultShows the original regular expression.
impl Display for Regex
fn fmt(&self, f: &mut Formatter<'_>) -> ResultShows the original regular expression.
impl FromStr for Regex
type Err = Error;fn from_str(s: &str) -> Result<Regex, Error>Attempts to parse a string into a regular expression
impl TryFrom<&str> for Regex
type Error = Error;fn try_from(s: &str) -> Result<Regex, Error>Attempts to parse a string into a regular expression
impl TryFrom<String> for Regex
type Error = Error;fn try_from(s: String) -> Result<Regex, Error>Attempts to parse a string into a regular expression
Auto Trait Implementations
impl Freeze for Regex
impl RefUnwindSafe for Regex
impl Send for Regex
impl Sync for Regex
impl Unpin for Regex
impl UnsafeUnpin for Regex
impl UnwindSafe for Regex
Blanket Implementations
impl<T> Any for Regex
where
T: 'static + ?Sized,
fn type_id(&self) -> TypeId
impl<T> Borrow<T> for Regex
where
T: ?Sized,
fn borrow(&self) -> &T
impl<T> BorrowMut<T> for Regex
where
T: ?Sized,
fn borrow_mut(&mut self) -> &mut T
impl<T> CloneToUninit for Regex
where
T: Clone,
unsafe fn clone_to_uninit(&self, dest: *mut u8)
impl<T> From<T> for Regex
fn from(t: T) -> TReturns the argument unchanged.
impl<T> ToOwned for Regex
where
T: Clone,
type Owned = T;fn to_owned(&self) -> Tfn clone_into(&self, target: &mut T)
impl<T> ToString for Regex
where
T: Display + ?Sized,
fn to_string(&self) -> String
impl<T, U> Into<U> for Regex
where
U: From<T>,
fn into(self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom<U> for Regex
where
U: Into<T>,
type Error = never;fn try_from(value: U) -> Result<T, never>
impl<T, U> TryInto<U> for Regex
where
U: TryFrom<T>,
type Error = <U as TryFrom<T>>::Error;fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>