How to use StringReplace “from bottom to global”?

Suppose I have an original string that looks like:

str1 = “erewrer<.rer>r33ere<><>rer\nrer

I want to get rid of all those discrete <...>s to get

“erewrerr33ererer\nrer”

I tried StringReplace

StringReplace[str1, “<" ~~ __ ~~ ">” -> “”]

but it produced

“erewrer”

which is the result with the outermost <...> removed.

What should I do?

=================

=================

1 Answer
1

=================

You need to add Shortest[] to get the shortest consistent match(es), since Mathematica uses Longest[] (i.e. a greedy match) by default:

StringReplace[“erewrer<.rer>r33ere<><>rer\nrer“,
Shortest[“<" ~~ __ ~~ ">“] -> “”]
“erewrerr33ererer\nrer”

1

 

Regex version: StringReplace[str1, RegularExpression[“<(?s).+?>“] -> “”]
– J. M.♦
Feb 23 at 5:30