Regex to convert CamelCase to snake case in Redshift

Viewed 584

I am trying to convert CamelCase to either snake case or separated by a delimiter using regex in SQL (AWS Redshift). So something like

regexp_replace(MyString, '([A-Z]+)', '-$1')

except I need to specify not at the beginning of the string. Right now,

MyString -> -my-string instead of my-string.

How do I do this?

1 Answers

Match and capture any char before the uppercase letters, and restore it using another backreference in the replacement pattern:

regexp_replace(MyString, '(.)([A-Z]+)', '$1-$2')
                          ^^^            ^^^^^

See the regex demo.

I understand you already LOWER the result after the regex replacement.

Related