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 newRegexobject using theRegex::newmethod. The\s+is a regular expression that matches one or more whitespace characters. Theunwrapmethod is used to convert theResulttype returned by theRegex::newmethod into aRegextype. -
let words = re.split("This is a string").collect::<Vec<&str>>();- This line uses thesplitmethod of theRegextype to split the string into words. Thecollectmethod is used to convert the iterator returned by thesplitmethod into aVec<&str>type.
Helpful links
Related
- How to replace a capture group using Rust regex?
- How to use regex lookbehind in Rust?
- How to match whitespace with a regex in Rust?
- Regex example to match multiline string in Rust?
- How to replace all matches using Rust regex?
- How to match the end of a line in a Rust regex?
- How to match a URL with a regex in Rust?
- How to use Unicode in a regex in Rust?
- How to replace strings using Rust regex?
- How to parse a file with Rust regex?
More of Rust
- How to use regex to match a double quote in Rust?
- How to create a HashMap of structs in Rust?
- How to replace a capture group using Rust regex?
- How to match the end of a line in a Rust regex?
- How to modify an existing entry in a Rust HashMap?
- How do I identify unused variables in Rust?
- How to use negation in Rust regex?
- Regex example to match multiline string in Rust?
- How to use a Rust HashMap in a struct?
- How do I use a variable number of arguments in Rust?
See more codes...