将CamelCase转换为snake_case

Yus*_*suf 1 sql postgresql

需要以下查询的结果

select regexp_replace('StackOverflow', 'something', 'something')
Run Code Online (Sandbox Code Playgroud)

stack_overflow
Run Code Online (Sandbox Code Playgroud)

a_h*_*ame 8

以下正则表达式在每个大写字母前添加下划线:

regexp_replace(name, '([A-Z])','_\1', 'g'))
Run Code Online (Sandbox Code Playgroud)

由于这会在开头产生下划线,因此需要使用 trim()

trim(both '_' from lower(regexp_replace(name, '([A-Z])','_\1', 'g')))
Run Code Online (Sandbox Code Playgroud)

以下查询:

with names (name) as (
  values ('StackOverflow'), 
         ('Foo'), 
         ('FooBar'), 
         ('foobar'), 
         ('StackOverflowCom')
)
select name, trim(both '_' from lower(regexp_replace(name, '([A-Z])','_\1', 'g'))) as new_name
from names;
Run Code Online (Sandbox Code Playgroud)

收益:

name             | new_name          
-----------------+-------------------
StackOverflow    | stack_overflow    
Foo              | foo               
FooBar           | foo_bar           
foobar           | foobar            
StackOverflowCom | stack_overflow_com
Run Code Online (Sandbox Code Playgroud)