Replacing brackets in a string

I have a string such as str = "MyFunction[x] = ...", where x is a value. How do I replace the square brackets with parentheses such that str contains "MyFunction(x) = ..."? There can be may different values x, and in my string there can also be other brackets that I don’t wish to replace (so I don’t wish to replace all occurrences, which I know how to do). Thanks.

If your x isn’t going to contain the closing bracket ] character, and these are going to be the first pair of brackets in your string, you can do either of the following:

julia> replace(str, '[' => '(', ']' => ')', count = 2)
"MyFunction(x) = ..."

julia> replace(str, r"\[(.*?)\]" => s"(\1)", count = 1)
"MyFunction(x) = ..."

1 Like

Not sure about the performance implications of replacing a longer string so benchmark if this is in a hot loop (although hopefully it isn’t!), but why not be explicit:

julia> replace(str, "MyFunction[x]" => "MyFunction(x)")
"MyFunction(x) = ..."

Perhaps use Regex captures like this? Strings · The Julia Language

julia> replace.(["MyFunction[x] = ...", "a = MyFunction[2]"], 
                 r"MyFunction\[(?<x>\w+)\]" => s"MyFunction(\g<x>)")
2-element Vector{String}:
 "MyFunction(x) = ..."
 "a = MyFunction(2)"