0

How can we insert and interpolate a Nim variable into its regex (procedure re( ... )) just like Perl does ?

itil memek cantik
  • 1,167
  • 2
  • 11

1 Answers1

1

Not quite sure why you posted this both here and on the Nim community forums. But if this comes up in someone elses search you can find my original response here. The answer is as follows:

Since the re module and re procedure takes a raw string literal you can use fmt from strformat to do this:

import re, strformat

let
  num = r"\d*"
  wordNum = re(fmt"[a-z]\w*{num}")
  wordNum2 = re"[a-z]\w*\d*"

echo find("hello123", wordNum)
echo find("hello123", wordNum2)

echo find("       hello123", wordNum)
echo find("       hello123", wordNum2)

Note that the num string needs to be a raw literal as well, or you'd have to escape the backslash.

PMunch
  • 1,525
  • 11
  • 20