我正在尝试将连字符字符串转换为CamelCase字符串。将连字符转换为骆驼大小写
(defn hyphenated-name-to-camel-case-name [^String method-name]
(clojure.string/replace method-name #"-(w)"
#(clojure.string/upper-case (first %1))))
(hyphenated-name-to-camel-case-name "do-get-or-post")
==> do-Get-Or-Post
为什么我仍然得到的破折号输出字符串?
您应该将first
替换为second
:
(defn hyphenated-name-to-camel-case-name [^String method-name]
(clojure.string/replace method-name #"-(w)"
#(clojure.string/upper-case (second %1))))
您可以通过在代码中插入println
来检查clojure.string/upper-case
获得的参数:
(defn hyphenated-name-to-camel-case-name [^String method-name]
(clojure.string/replace method-name #"-(w)"
#(clojure.string/upper-case
(do
(println %1)
(first %1)))))
当你运行上面的代码时,结果是:
[-g g]
[-o o]
[-p p]
vector的第一个元素是匹配的字符串,第二个元素是捕获的字符串,这意味着你应该使用second
,而不是first
。
如果您的目标只是在不同情况下进行转换,我真的很喜欢骆驼-蛇-烤肉串库。->CamelCase
是所讨论的函数名。
受此启发,您也可以做
(use 'clojure.string)
(defn camelize [input-string]
(let [words (split input-string #"[s_-]+")]
(join "" (cons (lower-case (first words)) (map capitalize (rest words))))))