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 strings using Rust regex?
- Regex example to match multiline string in Rust?
- 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 use negation in Rust regex?
- How to use regex lookbehind in Rust?
- How to use regex lookahead in Rust?
- How to ignore case in Rust regex?
More of Rust
- Regex example to match multiline string in Rust?
- How to use regex to match a double quote in Rust?
- How to print a Rust HashMap?
- How to map a Rust slice?
- How to create a HashMap of structs in Rust?
- How to use regex captures in Rust?
- How to replace a capture group using Rust regex?
- How to replace all matches using Rust regex?
- How to use non-capturing groups in Rust regex?
See more codes...