Convert Ruby string to *nix filename-compatible string -



Convert Ruby string to *nix filename-compatible string -

in ruby have arbitrary string, , i'd convert valid unix/linux filename. doesn't matter looks in final form, long visually recognizable string started as. possible examples:

"here's string!" => "heres_my_string" "* asterisk, see" => "is_an_asterisk_you_see"

is there built-in (maybe in file libraries) accomplish (or close this)?

by specifications, accomplish regex replacement. regex match characters other basic letters , digits:

s/[^\w\s_-]+//g

this remove whitespace in between words, shown in examples:

s/(^|\b\s)\s+($|\s?\b)/\\1\\2/g

and lastly, replace remaining spaces underscores:

s/\s+/_/g

here in ruby:

def friendly_filename(filename) filename.gsub(/[^\w\s_-]+/, '') .gsub(/(^|\b\s)\s+($|\s?\b)/, '\\1\\2') .gsub(/\s+/, '_') end

ruby string filenames

Comments

Popular posts from this blog

iphone - Dismissing a UIAlertView -

intellij idea - Update external libraries with intelij and java -

javascript - send data from a new window to previous window in php -