rustHow to split a string by regex in Rust?
Splitting a string by regex in Rust can be done using the str::split
method. This method takes a &str
and a &str
representing a regular expression as arguments and returns an iterator over the substrings of the given string slice, separated by the regular expression.
Example code
let s = "Hello, world!";
let re = r"\W+";
for part in s.split(re) {
println!("{}", part);
}
Output example
Hello
world
Code explanation
let s = "Hello, world!";
: This line declares a&str
variables
and assigns it the value"Hello, world!"
.let re = r"\W+";
: This line declares a&str
variablere
and assigns it the valuer"\W+"
, which is a regular expression representing one or more non-word characters.for part in s.split(re)
: This line uses thestr::split
method to split the strings
by the regular expressionre
and iterate over the resulting substrings.println!("{}", part);
: This line prints each substring to the console.
Helpful links
Related
- How to match a URL with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to replace all matches using Rust regex?
- Regex example to match multiline string in Rust?
- How to use Unicode in a regex in Rust?
- How to split a string with Rust regex?
- How to get a capture group using Rust regex?
- How to use non-capturing groups in Rust regex?
- How to match the end of a line in a Rust regex?
- How to match whitespace with a regex in Rust?
More of Rust
- How to use regex to match a double quote in Rust?
- How to use a tuple as a key in a Rust HashMap?
- Hashshet example in Rust
- How to find the first match in a Rust regex?
- How to serialize JSON in Rust?
- How to set the lifetime of a Rust HashMap?
- How to loop through a Rust HashMap?
- How to convert the keys of a Rust HashMap to a vector?
- How to split a string with Rust regex?
- How to match the end of a line in a Rust regex?
See more codes...