Skip to content

Commit

Permalink
add named captures, groups and references
Browse files Browse the repository at this point in the history
  • Loading branch information
ificiana committed Sep 8, 2022
1 parent c4f0b63 commit 9248b44
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
8 changes: 8 additions & 0 deletions remagic/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,11 @@ def after(pattern):

def not_after(pattern):
return rf"(?<!={Pattern(pattern)})"


def ref(reference):
if isinstance(reference, int) and reference > 0:
return rf"\{reference}"
elif isinstance(reference, str):
return rf"(?P={reference})"
return Pattern(reference)
13 changes: 13 additions & 0 deletions remagic/pattern.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,19 @@ def add(self, other: Union[str, "Pattern"]):
def repeat(self, num: Union[int, Tuple[int, int]]) -> "Pattern":
return self * num

def label(self, name):
return Pattern(rf"(?P<{name}>{self._pattern})")

def group(self):
return Pattern(rf"({self._pattern})")

def ref(self, reference):
if isinstance(reference, int) and reference > 0:
return self.add(rf"\{reference}")
elif isinstance(reference, str):
return self.add(rf"(?P={reference})")
return self.add(Pattern(reference))

@property
def pattern(self) -> str:
return self._pattern
Expand Down
31 changes: 31 additions & 0 deletions tests/test_refs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# flake8: noqa

import pytest

from remagic import *


@pytest.mark.parametrize(
"capture, name, expected_output",
[
("captured", "text", "(?P<text>captured)(?P=text)"),
],
)
def test_refs(capture, name, expected_output):
output = create(capture).label("text").ref("text")
assert output._pattern == expected_output, "{} != {}".format(
output, expected_output
)


@pytest.mark.parametrize(
"capture, expected_output",
[
("captured", r"(captured)\1"),
],
)
def test_groups(capture, expected_output):
output = create(capture).group().ref(1)
assert output._pattern == expected_output, "{} != {}".format(
output, expected_output
)

0 comments on commit 9248b44

Please sign in to comment.