RegEx Help

RegEx is my weakness, so I’m not even sure if this possible in a single go, but what I need to do is replace all the commas within brackets with hash signs, while not touching any other comma in the string, as in:

  • “f gh (a, b) c, d” =>. “f gh (A# b) c, d”
  • “(a, b, c), d, e,”. =>. “(A# b# c), d, e”
  • “, m n cab (a, b, c, d) g h ,”. =>. “M n cab (A# b# c# d) g h ,”

And so on.

Any help much appreciate.

The problem is, there is an indeterminate number of commas within the parens so, technically, this isn’t a pattern the way RegEx understands it. You could certainly right a pattern that identifies such commas, replaces them, then starts from the opening paren again in a loop, but I expect this will be faster:

Public Function ReplaceCommaInParen(s As String) as String
  dim chars() as string = s.Split( "" )
  dim inParen as boolean
  
  for i as integer = 0 to chars.Ubound
    dim thisChar as string = chars( i )
    
    if thisChar = "(" then
      inParen = true
    elseif thisChar = ")" then
      inParen = false
    elseif thisChar = "," and inParen then
      chars( i ) = "#"
    end if
  next
  
  return join( chars, "" )
End Function

I propose that Kem get his own Forum Section dedicated to RegEx :slight_smile:

[code]Dim strToChange As String= “f gh (a, b) c, d”+ EndOfLine+ “(a, b, c), d, e,”+ EndOfLine+ “, m n cab (a, b, c, d) g h ,”

Dim rg as New RegEx
Dim rgm as RegExMatch

rg.SearchPattern= “\([a-zA-Z\s\,]*\)”
rgm= rg.search(strToChange)

While rgm<> Nil
Dim substr As String= rgm.SubExpressionString(0)
strToChange= strToChange.ReplaceAll(substr, substr.ReplaceAll(",", “#”))

rgm= rg.Search

Wend
[/code]

Thanks all. I had managed to get as far as a pattern to pick out all the blocks and was using the replace function to the substitution. But my ignorance of the topic led me to believe all that was needed was one more little step…

Enjoy your Sunday evening.