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?

1
  • This solves your problem - \\mintinline\{julia}\{|}(?= ). Commented Sep 17, 2021 at 6:58

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.