DigitalRoss的答案将无法识别 CamelCase 中嵌入的首字母缩略词。例如,它将“MyHTMLTricks”拆分为“My HTML Tricks”而不是“My HTML Tricks”。
这是基于PmWikiAsSpaced()
中的函数的另一个选项,它在对此类情况敏感方面做得很好:
"MyHTMLTricks" \
.gsub(/([[:lower:]\\d])([[:upper:]])/, '\1 \2') \
.gsub(/([^-\\d])(\\d[-\\d]*( |$))/,'\1 \2') \
.gsub(/([[:upper:]])([[:upper:]][[:lower:]\\d])/, '\1 \2')
=> "My HTML Tricks"
The other thing I like about this approach is that it leaves the string a string, instead of transforming it into an array. If you really want the array, then just add a split at the end.
"MyHTMLTricks" \
.gsub(/([[:lower:]\\d])([[:upper:]])/, '\1 \2') \
.gsub(/([^-\\d])(\\d[-\\d]*( |$))/,'\1 \2') \
.gsub(/([[:upper:]])([[:upper:]][[:lower:]\\d])/, '\1 \2') \
.split
=> ["My", "HTML", "Tricks"]
For the record, here is the original PHP code from PmWiki.
function AsSpaced($text) {
$text = preg_replace("/([[:lower:]\\d])([[:upper:]])/", '$1 $2', $text);
$text = preg_replace('/([^-\\d])(\\d[-\\d]*( |$))/', '$1 $2', $text);
return preg_replace("/([[:upper:]])([[:upper:]][[:lower:]\\d])/", '$1 $2', $text);
}