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 replace a capture group using Rust regex?
- How to replace all matches using Rust regex?
- How to use Unicode in a regex in Rust?
- How to match whitespace with a regex in Rust?
- How to match a URL with a regex in Rust?
- How to get a capture group using Rust regex?
- How to replace strings using Rust regex?
- How to use 'or' in Rust regex?
- How to use non-capturing groups in Rust regex?
More of Rust
- How to replace a capture group using Rust regex?
- How to use Unicode in a regex in Rust?
- How to match a URL with a regex in Rust?
- Hashshet example in Rust
- How to convert a slice of bytes to a string in Rust?
- How to replace all matches using Rust regex?
- How to replace strings using Rust regex?
- How to use non-capturing groups in Rust regex?
- Rust map function example
See more codes...