From c81c7d15d34e949d33ae68d56087a170582cd491 Mon Sep 17 00:00:00 2001 From: Stephen Rosen Date: Mon, 4 Nov 2024 11:37:51 -0600 Subject: [PATCH] Add support for passing flags as strings resolves #51 There is no support for `Flags` structs as provided by the `regress` crate. But a string can be passed down and is converted to Flags by the `with_flags` constructor. Exposing flags as a struct/enum adds significant complexity deemed not worth the additional code at this time. (See #51 for more details.) A python test verifies that the alternate constructor pattern works and provides support for the `"u"` flag. --- src/lib.rs | 15 +++++++++++---- tests/test_regress.py | 14 +++++++++++++- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index b70ce9d..e2df317 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -12,10 +12,17 @@ struct RegexPy { #[pymethods] impl RegexPy { #[new] - fn init(value: &str) -> PyResult { - match Regex::new(value) { - Ok(inner) => Ok(RegexPy { inner }), - Err(e) => Err(RegressError::new_err(e.to_string())), + #[pyo3(signature = (value, flags=None))] + fn init(value: &str, flags: Option<&str>) -> PyResult { + match flags { + Some(f) => match Regex::with_flags(value, f) { + Ok(inner) => Ok(RegexPy { inner }), + Err(e) => Err(RegressError::new_err(e.to_string())), + }, + None => match Regex::new(value) { + Ok(inner) => Ok(RegexPy { inner }), + Err(e) => Err(RegressError::new_err(e.to_string())), + }, } } diff --git a/tests/test_regress.py b/tests/test_regress.py index f536e43..c8e4f1d 100644 --- a/tests/test_regress.py +++ b/tests/test_regress.py @@ -1,5 +1,4 @@ import pytest - import regress @@ -60,3 +59,16 @@ def test_error_handling(): pass else: pytest.fail("error not reached") + + +def test_with_flags(): + # "L" for letters, "Z" for spaces, "N" for numerics + pattern = r"^\p{L}\p{Z}\p{N}$" + + regex = regress.Regex(pattern, flags="u") + flagless_regex = regress.Regex(pattern) + + match = regex.find("a 0") + flagless_match = flagless_regex.find("a 0") + assert match is not None + assert flagless_match is None