将 CamelCase 转换为 snake_case [英] Convert CamelCase to snake_case

查看:77
本文介绍了将 CamelCase 转换为 snake_case的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要以下查询的结果

select regexp_replace('StackOverflow', 'something', 'something')

作为

stack_overflow

推荐答案

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

The following regex adds an underscore in front of every uppercase letter:

regexp_replace(name, '([A-Z])','_\1', 'g'))

由于这会导致开头带有下划线,因此需要使用 trim()

As that results in on underscore at the beginning, this needs to be removed using trim()

trim(both '_' from lower(regexp_replace(name, '([A-Z])','_\1', 'g')))

以下查询:

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;

返回:

name             | new_name          
-----------------+-------------------
StackOverflow    | stack_overflow    
Foo              | foo               
FooBar           | foo_bar           
foobar           | foobar            
StackOverflowCom | stack_overflow_com

这篇关于将 CamelCase 转换为 snake_case的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆