How can I highlight the nested parentheses?

Suppose I have the following sentence:

This is a (string) with lots of (brackets) and (to make ((the fun) complete) some are) even nested. 

      

I need an easy way to isolate all the inner braces as I need to replace them with curly braces. So this line looks like this

This is a (string) with lots of (brackets) and (to make {{the fun} complete} some are) even nested.

      

In theory, this means that I need a regex that selects in the first round all left parentheses that are preceded by another left parenthesis and all right parentheses followed by another right parenthesis during the next round. This way I can use regex replacement to replace the rounded curly braces.

But I keep fighting ... I tried something like this but it clearly doesn't work, no advice?

(?<=\([^()]*)\(

      

[EDIT]

Well, actually I was able to get it to work (using VBA btw), but probably purists might not be very impressed, so any advice for improvement is always appreciated. I did a two step approach, first I replace every left parenthesis that is preceded by another left parenthesis and replace it with a curly one. Then I replace the right bracket, which is preceded by curly, with a closing curly. And this loop ... Works well at the end, but of course, only if there are no curly ones that are already used elsewhere

Sub testMyFunc()
Call replaceNestedBrackets("This is a (comment in a) string folowed by a (nested and (more (complex)) with (blabla)) comment")
End Sub



Function replaceNestedBrackets(s As String) As String

Dim regEx As New RegExp
regEx.Global = True
Dim colregmatch As MatchCollection
Dim r1, r2 As String
r1 = "{"
r2 = "}"

regEx.Pattern = "(.*\([^)]*)(\()(.*)"

Set colregmatch = regEx.Execute(s)
If colregmatch.Count > 0 Then
    s = colregmatch.Item(0).SubMatches.Item(0) & r1 & colregmatch.Item(0).SubMatches.Item(2)

    regEx.Pattern = "([^{]*{[^\)]*)(\))(.*)"
    Set colregmatch = regEx.Execute(s)
    s = colregmatch.Item(0).SubMatches.Item(0) & r2 & colregmatch.Item(0).SubMatches.Item(2)

    replaceNestedBrackets (s)
End If
replaceNestedBrackets = s

Debug.Print replaceNestedBrackets
End Function

      

+3


source to share


2 answers


Try

(\([^()]*)\(([^()]*)\)

      



Replace with \1{\2}

. This will replace the parentheses from the inside out, so you'll have to apply it until it no longer matches.

See demo .

+1


source


How about a two step replacement as shown below. Apologies for my code being in Powershell, but its regexes are the important bit.

$x = "This is a (string) with lots of (brackets) and (to make ((the fun) complete) some are) even nested."
$x = $x -replace '(?<=\([^\)]+)\(', '{'
$x = $x -replace '\)(?=[^\(]+\))', '}'

      



Not fully tested, but works for your example.

+1


source







All Articles