Skip to content

Instantly share code, notes, and snippets.

@rabestro
Last active May 6, 2025 19:55
Show Gist options
  • Save rabestro/cc893086420b0deb22c0072f32d2ac12 to your computer and use it in GitHub Desktop.
Save rabestro/cc893086420b0deb22c0072f32d2ac12 to your computer and use it in GitHub Desktop.
Convert a long phrase to its acronym.

Acronym

Convert a long phrase to its acronym

Java

import java.util.function.Supplier;  
import java.util.regex.MatchResult;  
import java.util.regex.Pattern;  
import java.util.stream.Collectors;  
  
record Acronym(String phrase) implements Supplier<String> {  
    private static final Pattern FIRST_LETTER_PATTERN =  
            Pattern.compile("(?<![\\p{Alpha}'])\\p{Alpha}");  
  
    public String get() {  
        return FIRST_LETTER_PATTERN  
                .matcher(phrase)  
                .results()  
                .map(MatchResult::group)  
                .collect(Collectors.joining())  
                .toUpperCase();  
    }  
}

Scala

object Acronym:  
  private val FirstLetter = raw"(?<![\p{Alpha}'])\p{Alpha}".r  
  
  def abbreviate(phrase: String): String =  
    FirstLetter.findAllIn(phrase).mkString.toUpperCase

Groovy

class Acronym {  
    static String abbreviate(String phrase) {  
        phrase.findAll(/(?<![\p{Alpha}'])\p{Alpha}/)  
                .join().toUpperCase()  
    }  
}

Kotlin

object Acronym {  
    private val FIRST_LETTER_REGEX =   
        Regex("""(?<![\p{Alpha}'])\p{Alpha}""")  
  
    fun generate(phrase: String): String {  
        return FIRST_LETTER_REGEX  
            .findAll(phrase)  
            .map { it.value }  
            .joinToString("")  
            .uppercase()  
    }  
}

AWK

BEGIN {
    RS = "[^[:alnum:]']"
    ORS = FS = ""
}
{
    print toupper($1)
}

Power Query M formula language

(phrase as text) as text =>
    let
        Words = Text.SplitAny(phrase, " -_"),
        FirstLetters = List.Transform(Words, each Text.Start(_, 1)),
        Acronym = Combiner.CombineTextByDelimiter("")(FirstLetters)
    in
        Text.Upper(Acronym)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment