Rust Requires Chilkat v11.7.0+
Rust
Search a PDF with a Regular Expression
See more PDF Text Extraction Examples
Demonstrates searching a PDF with a regular expression (regex: true), limiting the number of results (maxResults), and matching whole words only (wholeWord).Chilkat Rust Downloads
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// The PDF used in this example is available at order_records.pdf
let pdf = chilkat::Pdf::new();
if pdf.load_file("qa_data/pdf/order_records.pdf").is_err() {
println!("{}", pdf.last_error_text());
return;
}
let json = chilkat::JsonObject::new();
let json_out = chilkat::JsonObject::new();
// Find every order number. With regex set to true, the query is a regular expression.
let _ = json.update_string("query", "ORD-[0-9]{4}-[0-9]{4}");
let _ = json.update_bool("regex", true);
// We only want the matched text, so no context is needed.
let _ = json.update_int("context", 0);
if pdf.extract_text("search", &json, &json_out).is_err() {
println!("{}", pdf.last_error_text());
return;
}
println!("Order numbers found: {}", json_out.int_of("count"));
let mut i = 0;
let mut count_i = json_out.size_of_array("matches");
while i < count_i {
json_out.set_i(i);
println!("{}", json_out.string_of("matches[i].text").unwrap_or_default());
i = i + 1;
}
// Find the e-mail addresses, but stop after the first three.
let _ = json.update_string("query", "[a-z0-9._]+@[a-z]+[.][a-z]+");
let _ = json.update_int("maxResults", 3);
if pdf.extract_text("search", &json, &json_out).is_err() {
println!("{}", pdf.last_error_text());
return;
}
println!("First three e-mail addresses:");
i = 0;
count_i = json_out.size_of_array("matches");
while i < count_i {
json_out.set_i(i);
println!("{}", json_out.string_of("matches[i].text").unwrap_or_default());
i = i + 1;
}
// wholeWord: true matches only whole words. The word "cat" appears once in the PDF,
// but it is also inside "catalog" and "category".
let _ = json.delete("maxResults");
let _ = json.update_bool("regex", false);
let _ = json.update_string("query", "cat");
if pdf.extract_text("search", &json, &json_out).is_err() {
println!("{}", pdf.last_error_text());
return;
}
println!("Occurrences of cat (any): {}", json_out.int_of("count"));
let _ = json.update_bool("wholeWord", true);
if pdf.extract_text("search", &json, &json_out).is_err() {
println!("{}", pdf.last_error_text());
return;
}
println!("Occurrences of cat (whole word): {}", json_out.int_of("count"));
// Sample output:
// Order numbers found: 9
// ORD-2026-0301
// ORD-2026-0302
// ORD-2026-0303
// ORD-2026-0304
// ORD-2026-0305
// ORD-2026-0306
// ORD-2026-0307
// ORD-2026-0308
// ORD-2026-0307
// First three e-mail addresses:
// alice.moore@example.com
// bkumar@example.org
// carla@example.net
// Occurrences of cat (any): 3
// Occurrences of cat (whole word): 1