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

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