簡體   English   中英

將 CamelCase 轉換為 snake_case

[英]Convert CamelCase to snake_case

需要以下查詢的結果

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

作為

stack_overflow

以下正則表達式在每個大寫字母前添加一個下划線:

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

由於這會在一開始出現下划線,因此需要使用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

我想你想在這里

lower(
  regexp_replace(
    replace(column_name, ' ', '_'),
    '([[:lower:]])([[:upper:]])',
    '\1_\2',
    'g'
  )
)

在這里我們測試一下

WITH t (name) as (
  VALUES ('StackOverflow'), 
    ('Foo'), 
    ('FooBar'), 
    ('foobar'), 
    ('StackOverflowCom'),
    ('BLEHHHHokBaz')  -- doesn't go funky
)
SELECT name, lower(
  regexp_replace(
    replace(name, ' ', '_'),
    '([[:lower:]])([[:upper:]])',
    '\1_\2',
    'g'
  )
) AS new_name
FROM t;

與@a_horse_with_no_name相比,這具有優點,它可以使用連續的大寫字母,並且也可以解決空格。

另請參閱

SnakeCase 到 CamelCase

SELECT REPLACE(INITCAP('hamza_rajput'), '_',' ') as camel_case;

CamelCase 到 SnakeCase

SELECT LOWER(regexp_replace('hamzaRajput', '([A-Z])','_\1', 'g')) as snake_case;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM