首页 > 解决方案 > 将字符串中的 Pascal 大小写更改为蛇大小写

问题描述

我有以下文字:

SendNoticeMsg (api.post = "/test/SendNoticeMsg")
GenerateMsg (api.post = "/test/GenerateMsg")
GetUserLastAction (api.post = "/test/GetUserLastAction")

我想将文本更改为:

SendNoticeMsg (api.post = "/test/send_notice_msg")
GenerateMsg (api.post = "/test/generate_msg")
GetUserLastAction (api.post = "/test/get_user_last_action")

说明:我只想将 URL 路径更改为有效的下划线样式,因此解决方案不应更改任何其他不相关的字符。

我尝试使用 sed 脚本:

sed -E 's/(\/test\/.*)([A-Z]).*\"/\1\2_\L/'

但它不起作用。

标签: regexperlawksed

解决方案


perl -wnE'
    @p = m{(.*/)(.*)"};                       # break up into parts
    @w = $p[-1] =~ /([A-Z][a-z0-9]*)/g;       # extract (PascalCase-ed) words
    $p[-1] = join("_", map { lc } @w).q{")};  # low-case them, join with _ 
    say @p
' input.txt

或通过将开关更改为“就地”覆盖输入perl -i.bak -wnE'...'

这假设单词,在初始之后,只能有[a-z0-9]; 如果需要进行调整。


推荐阅读