π¦ Rust Master Class - Chapter 15: Text Processing
I wrote a letter to my ex. Not to get back together β just to say thank you. Finding the right words took hours. Text processing is hard. Finding meaning in those words is harder.
Rust provides a robust set of tools for text processing, file handling, and regular expressions, primarily through the standard libraryβs String, std::fs, and std::path modules, as well as the external regex crate.
1. Text Processing (Strings)
Rust distinguishes between two main types of strings: the string literal (&str), which is a fixed-length reference to string data, and the growable String type, which is a heap-allocated buffer .
-
Key Operations:
- Creation & Modification: Use
String::from()or.to_string()to create growable strings. You can append data using.push()(for single characters) or.push_str()(for string slices) [1-3]. - Concatenation: The
format!macro is a common way to combine multiple strings into a newStringwithout taking ownership of the original variables . - Cleanup: The
.trim()method removes leading and trailing whitespace .
- Creation & Modification: Use
-
Code Example:
// Create a mutable variable let mut s = String::from("Rust"); s.push_str(" Programming"); // s is now "Rust Programming" // Create a new variable let first = "the developer".to_string(); // Create a new variable let last = "developer".to_string(); // Create a new variable let full = format!("{} {}", first, last); // Concatenation via macro
2. File and Directory Handling
File management in Rust is handled by the std::fs and std::path modules. Most of these operations return a std::io::Result, which should be handled to manage potential errors (e.g., file not found) .
-
Key Concepts:
- File Operations: You can create, rename, copy, and remove files using
fs::create_file,fs::rename,fs::copy, andfs::remove_file. - Directory Operations: Use
fs::create_dirfor a single folder orfs::create_dir_allto create a nested path. Conversely,fs::remove_dir_allwill delete a directory and its contents . - Path Management: The
Path::new()function is used to define cross-platform file paths .
- File Operations: You can create, rename, copy, and remove files using
-
Code Example:
use std::fs; use std::path::Path; fn manage_files() -> std::io::Result<()> { // Create a new variable let path = Path::new(r"D:\my_text.txt"); // fs::File::create(path)?; // Create a file fs::rename(r"D:\prev.txt", r"D:\new.txt")?; // Rename fs::copy(r"D:\new1.txt", r"D:\new2.txt")?; // Copy fs::remove_dir_all(r"D:\rust1")?; // Remove directory and contents Ok(()) }
3. Regular Expressions (Regex)
Regular expressions are not part of the Rust standard library; they require the regex crate. This crate allows you to search, match, and capture patterns within text .
-
Key Concepts:
- Repetitions and Quantifiers: Patterns can include
?(0 or 1),*(0 or more),+(1 or more), or specific counts like{3,5}(between 3 and 5 occurrences) . - Word Boundaries: The
\banchor is used to match patterns at the start or end of words . - Captures: The
captures_itermethod allows you to iterate over every match found in a body of text .
- Repetitions and Quantifiers: Patterns can include
-
Code Example:
extern crate regex; use regex::Regex; fn main() { // Match words between 3 and 5 characters long // Create a new variable let re = Regex::new(r"\b\w{3,5}\b").unwrap(); // Create a new variable let text = "Hello i think you are happy"; for cap in re.captures_iter(text) { // Output to console println!("Match: {}", &cap); // Iterates through all matches } }
4. Error Handling with the Question Mark (?)
When working with files or parsing text, errors are common. Rust uses the question mark operator (?) as a shorthand for error propagation . If an operation returns an Err, the function returns early with that error; if it is Ok, it unwraps the value and continues .
π Download the full PDF: https://drive.google.com/file/d/1lgr83vSnAwGYCzVHQgVUYW2z5xNI4T4F/view?usp=sharing
Part 15 of the Rust Master Class series β STEM EdTech | Automation Consulting | Rust Tutoring
RustLang #Programming #LearnToCode #STEM #EdTech
π Practice Resources
GitHub Repository: https://github.com/PacktPublishing/Rust-Programming-Master-Class-from-Beginner-to-Expert
Try it yourself: https://play.rust-lang.org/
Run the code from this chapter in the Rust playground, then clone the repo to continue your Rust journey!
Part 15 of the Rust Master Class series β STEM EdTech | Automation Consulting | Rust Tutoring
Top comments (0)