jasonwood Posted December 21, 2013 Posted December 21, 2013 How would I write a calculation to replace all non-alphanumeric characters with an underscore? For example ABC 123 (hello.world!) would become ABC_123__hello_world__
Lee Smith Posted December 22, 2013 Posted December 22, 2013 Like this? Substitute ( Text ; [ " " ; "_" ] ; [ "(" ; "_" ] ; [ "." ; "_" ] ; [ "!" ; "_" ] ; [ ")" ; "_" ] )
Brooks Posted December 22, 2013 Posted December 22, 2013 There are probably better approaches but two options are 1. Build a recursive function to run each character through alphanumeric filter and if empty replace with _ or 2. a long substitution string substituting each possible character with _. I'm not in front of a computer at the moment to right a cf example but look into recursive custom functions. That's the direction I would go. 1
comment Posted December 22, 2013 Posted December 22, 2013 How would I write a calculation to replace all non-alphanumeric characters with an underscore? I think we need a better definition of what is a "non-alphanumeric character" - or possibly, what is an "alphanumeric character". I suspect there may be an awful lot of characters in both categories - too many to consider each one individually. Perhaps it woud be best if you explained what type of input is expected here and - even ore importantly - what is the purpose of this exercise.
jasonwood Posted December 22, 2013 Author Posted December 22, 2013 Recursive function is the answer. Here's what I came up with: ReplaceOtherChars ( string ; ignorechars ; replacechars ) If ( Filter ( Left ( string ; 1 ) ; ignorechars ) = "" ; replacechar ; Left ( string ; 1 ) ) & If ( Length ( string ) > 1 ; ReplaceOtherChars ( Right ( string ; Length ( string ) - 1 ) ; ignorechars ; replacechar ) ; "" ) Example: ReplaceOtherChars ( "ABC 123 (hello.world!)" ; "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" ; "_" ) Output: ABC_123__hello_world__ The reason I needed this is because native AppleScript no longer works for changing printers in Mac OS X v 10.9 Mavericks because "Printer Setup Utility" is no longer included, so I've realized that rather than installing an old version of Printer Setup Utility, I can just use the lpoptions terminal command to change printers, but the printer name seems to require all non-alphanumeric characters replaced with underscores, otherwise the command fails. (I still want users to be able to enter & view their printer names normally so this custom function will be used each time the printer is changed)
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now