Regular Expression to generate acronym from any string of words using ColdFusion

Viewed 103

I am looking for a regular expression to generate acronym from any string. Say I have a string like "Apple Banana Cake" then the result is "ABC". Another example is "1 Banana 2 Orange" then the result is "1B2O"

I tried as given below as mentioned here - How to get the acronym from any string? but that does not work as expected.

writeDump(reReplaceNoCase('Apple Banana Carrot','[\\B.|\\P{L}]','','ALL'));
writeDump(reReplaceNoCase('Apple Banana Carrot','[\\B.|\\P]','','ALL'));
1 Answers

You can use

writeDump(reReplaceNoCase('Apple Banana Carrot','\B[a-zA-Z]|[^0-9a-zA-Z]','','ALL'));

See the regex demo. Details:

  • \B[a-zA-Z] - an ASCII letter that is preceded with a word char
  • | - or
  • [^0-9a-zA-Z] - any non-alphanumeric char from the ASCII set.
Related