I'm trying to implement in Nim, the following line of Python
addr_strs = re.findall(" address='0x([0-9a-f]{8})' ", file_contents)
The re.findAll() in Nim doesn't seem to handle captures, so I am filling in this missing piece. I have code that works, but it has a bit of hard-coded badness:
iterator genRegexCaptures(s: string, pattern: Regex): string =
var captured: array[1, string]
var idx = s.find(pattern, captured)
while idx != -1:
yield captured[0]
idx = s.find(pattern, captured, idx + 1)
proc get_addrs_from_map_file(fn: string): seq[uint] =
let file_contents = open(fn).readAll()
for addr_str in genRegexCaptures(file_contents, re" address='0x([0-9a-f]{8})' "):
result.add(fromHex[uint](addr_str))
The badness is that the caller specifies the Regex object, including the number of captures implicit in the re string, BUT genRegexCaptures() is hardcoded to support only one capture. How do I make genRegexCaptures support an arbitrary number of captures?
I'm hoping there is something more elegant than a simple generic:
iterator genRegexCaptures[T](s: string, pattern: Regex): string =
var captured: T
...
yuck:
for addr_str in genRegexCaptures[array[1, string]](file_contents, re" address='0x([0-9a-f]{8})' "):
result.add(fromHex[uint](addr_str))