Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for passing flags as strings #52

Merged
merged 2 commits into from
Nov 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion regress.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ from __future__ import annotations

from typing import Iterable

class RegressError(Exception): ...

class Regex:
def __init__(self, pattern: str): ...
def __init__(self, pattern: str, flags: str | None = None): ...
def find(self, text: str) -> Match | None: ...
def find_iter(self, text: str) -> Iterable[Match] | None: ...

Expand Down
15 changes: 11 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,17 @@ struct RegexPy {
#[pymethods]
impl RegexPy {
#[new]
fn init(value: &str) -> PyResult<Self> {
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<Self> {
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())),
},
}
}

Expand Down
13 changes: 13 additions & 0 deletions tests/test_regress.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,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