Using Regex() function, how do I match the end of the string?

I am using the Regex() function to create a regular expression pattern, instead of just using r"", because I need to interpolate a variable.

If I write Regex("$(f)$") - interpolating the variable f and wanting to match where it is at the end of a string - I get the error

identifier or parenthesized expression expected after $ in string

OK - but then how do I represent the end of the string?

Searching the web for “Julia Regex end of string” just gives me various lectures on how to write regular expressions.

The problem here is that the $ is being evaluated as a normal Julia string, and so it signifies interpolation, which is not the case when using the r"" macro.

The solution is to escape the last $ so that it’s interpreted as a literal character $, not an interpolation operator:

f = "an interpolated value"
Regex("$(f)\$")
2 Likes

I don’t know your use case, but you might be able to use *, as Julia Regex values support concatenation with strings

julia> rx = "a normal string" * r"$"
r"\Qa normal string\E(?:$)"

julia> match(rx, "this is a normal string")
RegexMatch("a normal string")

julia> match(rx, "this is a non-matching string")

julia>
1 Like

Thank you - I was avoiding doing that because I thought that escaping it would mean it got interpreted as a literal $ character not as an end of string indicator!

That makes sense! Escaping in Regex is already tedious, and combined with standard string handling it leaves a lot of room for confusion.

For the sake of clarity, here’s how the process works, with an example not using interpolation, Regex("hello\$")

  1. the string within the expression "hello\$" is evaluated first, and results in the value hello$ because of the escaped $
  2. The value hello$ is passed to the Regex constructor which processes it as a regular expression, which interprets the $ as “end of string”

When you use r"" you are skipping step 1, and whatever you write in that string is passed directly to Regex, with no string “evaluation” step beforehand.

Hence, you can write a regular expression directly: r"hello$"

2 Likes