rustHow to split a string with Rust regex?
Rust regex can be used to split a string into multiple parts. The split
method of the Regex
type can be used to split a string. The following example code splits a string into words using a space as the delimiter:
let re = Regex::new(r"\s+").unwrap();
let words = re.split("This is a string").collect::<Vec<&str>>();
The output of the above code is:
["This", "is", "a", "string"]
The code consists of the following parts:
-
let re = Regex::new(r"\s+").unwrap();
- This line creates a newRegex
object using theRegex::new
method. The\s+
is a regular expression that matches one or more whitespace characters. Theunwrap
method is used to convert theResult
type returned by theRegex::new
method into aRegex
type. -
let words = re.split("This is a string").collect::<Vec<&str>>();
- This line uses thesplit
method of theRegex
type to split the string into words. Thecollect
method is used to convert the iterator returned by thesplit
method into aVec<&str>
type.
Helpful links
Related
- How to match whitespace with a regex in Rust?
- How to match a URL with a regex in Rust?
- How to use non-capturing groups in Rust regex?
- How to replace a capture group using Rust regex?
- How to use Unicode in a regex in Rust?
- How to replace all matches using Rust regex?
- How to replace strings using Rust regex?
- How to parse a file with Rust regex?
- Regex example to match multiline string in Rust?
More of Rust
- How to use regex to match a group in Rust?
- How to convert a Rust HashMap to a BTreeMap?
- How to use regex to match a double quote in Rust?
- How to convert the keys of a Rust HashMap to a vector?
- How to convert a Rust slice of u8 to u32?
- How to convert a slice into an iter in Rust?
- How to replace a capture group using Rust regex?
- How to get the length of a Rust HashMap?
- How to get a capture group using Rust regex?
- How to match the end of a line in a Rust regex?
See more codes...