0

I want to convert the string

row = "how \\mintinline{julia}{Tuple{Matrix{Int16},Int16}} are \\mintinline{julia}{Tuple{Int8,Int16}} you"

to

"how `Tuple{Matrix{Int16},Int16}` are `Tuple{Int8,Int16}` you"

The script I tried is

replace(row, r"\\mintinline\{julia\}\{(.*?)\}"   => s"`\1`")

but the result is

"how `Tuple{Matrix{Int16},Int16`} are `Tuple{Int8,Int16`} you"

Is there a way to achieve this?

Likan Zhan
  • 1,056
  • 6
  • 14

1 Answers1

2

As you have seen it's not really a question of the longest or shortest match:

Longest:

julia> replace(row, r"\\mintinline\{julia\}\{(.*)\}"   => s"`\1`")
"how `Tuple{Matrix{Int16},Int16}} are \\mintinline{julia}{Tuple{Int8,Int16}` you"

Shortest:

julia> replace(row, r"\\mintinline\{julia\}\{(.*?)\}"   => s"`\1`")
"how `Tuple{Matrix{Int16`,Int16}} are `Tuple{Int8,Int16`} you"

but instead this is the classic problem of matching balanced parentheses.

This is definitely possible in PCRE (the library that Julia uses for regular expressions) using recursive patterns:

julia> replace(row, r"\\mintinline\{julia\}\{((\{(?1)\}|[^{}])*)\}"   => s"`\1`")
"how `Tuple{Matrix{Int16},Int16}` are `Tuple{Int8,Int16}` you"

The important part is ((\{(?1)\}|[^{}])* where (?1) applies this pattern recursively.

However, you are in my opinion approaching the limits of where regular expressions are useful and if you are continuing down this road you should perhaps look into parsing through other means.

ahnlabb
  • 2,017
  • 1
  • 6
  • 16