Skip to content
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
5 changes: 4 additions & 1 deletion src/fable-library-py/fable_library/reg_exp.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,10 @@ def _options_to_flags(options: int) -> int:
def create(pattern: str, options: int = 0) -> Pattern[str]:
# raw_pattern = pattern.encode("unicode_escape").decode("utf-8")
flags = _options_to_flags(options)
pattern = pattern.replace("?<", "?P<")
# Convert .NET named group syntax (?<name>...) to Python (?P<name>...).
# Only replace ?< when followed by a word character (name start), not by
# = or ! which are part of lookbehind assertions (?<=...) and (?<!...).
pattern = re.sub(r"\?<(?=[A-Za-z_])", "?P<", pattern)
return re.compile(pattern, flags=flags)


Expand Down
14 changes: 14 additions & 0 deletions tests/Python/TestRegex.fs
Original file line number Diff line number Diff line change
Expand Up @@ -636,3 +636,17 @@ let ``test doesn't succeed when not existing group without any named groups`` ()
let actual = r.Replace(text, replace)

actual |> equal expected

[<Fact>]
let ``test positive lookbehind works`` () =
let r = Regex @"(?<=A)\w+"
let text = "AB AC AD BD"
let ms = r.Matches(text) |> Seq.map (fun m -> m.Value) |> Seq.toList
ms |> equal [ "B"; "C"; "D" ]

[<Fact>]
let ``test negative lookbehind works`` () =
let r = Regex @"(?<!A)\d"
let text = "A1 B2 A3 C4"
let ms = r.Matches(text) |> Seq.map (fun m -> m.Value) |> Seq.toList
ms |> equal [ "2"; "4" ]
Loading