basic/
basic.rs

1use py_regex::{PyRegex, pyo3, pyo3::PyResult};
2use std::sync::Arc;
3use std::thread;
4
5fn main() -> PyResult<()> {
6    // Initialize Python for multithreaded usage.
7    pyo3::prepare_freethreaded_python();
8
9    let pattern = r"(?P<id>\d+)";
10    let text = "IDs: 101, 202, 303";
11    let re = Arc::new(PyRegex::new(pattern)?);
12
13    // Example usage of `search_match()` to obtain a `PyRegexMatch` object.
14    if let Some(m) = re.search_match(text)? {
15        println!("Full match (group 0): {:?}", m.group(0)?);
16        println!("Group 'id' (as group 0 here): {:?}", m.group(0)?);
17        println!("Groupdict: {:?}", m.groupdict()?);
18        println!("Span for group 0: {}..{}", m.start(0)?, m.end(0)?);
19    }
20
21    // Example of multithreaded usage of `find_iter()`, returning a `Vec<PyRegexMatch>`.
22    let mut handles = vec![];
23    for i in 0..4 {
24        let re_clone = Arc::clone(&re);
25        let text_clone = text.to_string();
26        let handle = thread::spawn(move || -> PyResult<()> {
27            let matches = re_clone.find_iter(&text_clone)?;
28            println!("Thread {}: found {} matches.", i, matches.len());
29            for m in matches {
30                println!("Thread {}: match group 0: {:?}", i, m.group(0)?);
31            }
32            Ok(())
33        });
34        handles.push(handle);
35    }
36
37    for handle in handles {
38        handle.join().unwrap()?;
39    }
40
41    Ok(())
42}