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 replace a capture group using Rust regex?
- How to replace strings using Rust regex?
- Regex example to match multiline string in Rust?
- How to get a capture group using Rust regex?
- How to get all matches from a Rust regex?
- How to find the first match in a Rust regex?
- How to extract data with regex in Rust?
- How to escape dots with regex in Rust?
More of Rust
- How to parse JSON string in Rust?
- Hashshet example in Rust
- How to use a custom hash function with a Rust HashMap?
- How to build a Rust HashMap from an iterator?
- How to replace strings using Rust regex?
- How to modify an existing entry in a Rust HashMap?
- How to yield return in Rust?
- How to escape dots with regex in Rust?
- How to convert JSON to a struct in Rust?
- How to clone a Rust HashMap?
See more codes...