def RemoveRegexBindingGroups(regex):
  """Replace binding parentheses in a regular expression.

  Identify all non-escaped open parentheses in the input regular
  expression and replace them with non-binding open parentheses so
  that they do not interfere with substring extraction.

  Args:
    regex: regular expression that may contain parentheses.

  Returns:
    The same regular expression but without binding groups.
  """

  result = []
  escaped = False
  for ch in regex:
    result.append('(?:' if ch == '(' and not escaped else ch)
    escaped = not escaped if ch == '\\' else False
  return ''.join(result)