sal/src/examples/text_replace_example.rs
2025-04-05 09:36:54 +02:00

93 lines
3.0 KiB
Rust

use std::error::Error;
use std::fs::File;
use std::io::Write;
use tempfile::NamedTempFile;
use sal::text::TextReplacer;
fn main() -> Result<(), Box<dyn Error>> {
// Create a temporary file for our examples
let mut temp_file = NamedTempFile::new()?;
writeln!(temp_file, "This is a foo bar example with FOO and foo occurrences.")?;
println!("Created temporary file at: {}", temp_file.path().display());
// Example 1: Simple regex replacement
println!("\n--- Example 1: Simple regex replacement ---");
let replacer = TextReplacer::builder()
.pattern(r"\bfoo\b")
.replacement("replacement")
.regex(true)
.add_replacement()?
.build()?;
let result = replacer.replace_file(temp_file.path())?;
println!("After regex replacement: {}", result);
// Example 2: Multiple replacements in one pass
println!("\n--- Example 2: Multiple replacements in one pass ---");
let replacer = TextReplacer::builder()
.pattern("foo")
.replacement("AAA")
.add_replacement()?
.pattern("bar")
.replacement("BBB")
.add_replacement()?
.build()?;
// Write new content to the temp file
writeln!(temp_file.as_file_mut(), "foo bar foo baz")?;
temp_file.as_file_mut().flush()?;
let result = replacer.replace_file(temp_file.path())?;
println!("After multiple replacements: {}", result);
// Example 3: Case-insensitive replacement
println!("\n--- Example 3: Case-insensitive replacement ---");
let replacer = TextReplacer::builder()
.pattern("foo")
.replacement("case-insensitive")
.regex(true)
.case_insensitive(true)
.add_replacement()?
.build()?;
// Write new content to the temp file
writeln!(temp_file.as_file_mut(), "FOO foo Foo fOo")?;
temp_file.as_file_mut().flush()?;
let result = replacer.replace_file(temp_file.path())?;
println!("After case-insensitive replacement: {}", result);
// Example 4: File operations
println!("\n--- Example 4: File operations ---");
let output_file = NamedTempFile::new()?;
let replacer = TextReplacer::builder()
.pattern("example")
.replacement("EXAMPLE")
.add_replacement()?
.build()?;
// Write new content to the temp file
writeln!(temp_file.as_file_mut(), "This is an example text file.")?;
temp_file.as_file_mut().flush()?;
// Replace and write to a new file
replacer.replace_file_to(temp_file.path(), output_file.path())?;
// Read the output file to verify
let output_content = std::fs::read_to_string(output_file.path())?;
println!("Content written to new file: {}", output_content);
// Example 5: Replace in-place
println!("\n--- Example 5: Replace in-place ---");
// Replace in the same file
replacer.replace_file_in_place(temp_file.path())?;
// Read the file to verify
let updated_content = std::fs::read_to_string(temp_file.path())?;
println!("Content after in-place replacement: {}", updated_content);
Ok(())
}