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) = ..."
1 Like

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)"

Hi, I also have problem/question removing brackets “[” and “]”.
I don’t fully understand the julia document page and PCRE2 page.

str1 = "['call', 'flight call']"
str2 = "['flight call']"
str1 * str2

I want the result like this " 'call', 'flight call', 'flight call' " .
I tried many regex replace(str1, regex => "") :

1.  r"\[(?<x>\w+)\]"
2.  r"\[(?\w+)\]"
3.  r"\[(?)\]"
4.  r"\[(*)\]"
5.  r"\[(\])"
6.  r"(\[)(\])"
7.  r"(\[)?\w+(\])"
8.  r"(\[)?(\])"
9.  r"(\[)*(\])"
10. r"(\[).(\])"

finally these 2 work ( but I feel they are not proper regex)

11. r"(\[)*(\])*")
12. r"(\[)?(\])?")

My question are

  • why 6, 8, 9, 10 don’t work
6.  r"(\[)(\])"
8.  r"(\[)?(\])"
9.  r"(\[)*(\])"
10. r"(\[).(\])"            # PCRE2 said . for any character
  • what is the better regex?

thanks!!

by modifying the 3rd and 4th patterns in the following way, the two square brackets are matched


ptn1=r"(\[)(\])"
ptn2=r"(\[)?(\])"
ptn3=r"(\[).*(\])"
ptn4=r"(\[).+(\])"  
julia> ptn3=r"(\[).*(\])"
r"(\[).*(\])"

julia> match(ptn3,str1)
RegexMatch("['call', 'flight call']", 1="[", 2="]") 

julia> ptn4=r"(\[).+(\])"            # PCRE2 said . for any character
r"(\[).+(\])"

julia> match(ptn4,str1)
RegexMatch("['call', 'flight call']", 1="[", 2="]") 

1 Like

now I understand from your examples ptn3 and ptn4, thank you.

People who end up in this discussion might find ReadableRegex.jl useful.

1 Like