One Line Regex Solution - Java and JavaScript


  • 2

    \b(cat|rat|bat).*?\b g

    Just replace the word with your capture!

    What'cha think?

    JavaScript

    var replaceWords = function(dict, sentence) {
        return sentence.replace( new RegExp(`\\b(${dict.join("|")}).*?\\b`, "g"), "$1" );
    };
    

    Java

    public String replaceWords(List<String> dict, String sentence) {
        return sentence.replaceAll("\\b("+String.join("|", dict)+").*?\\b", "$1");
    }
    

  • 2

    Just a shorter/simpler regex ending:

    public String replaceWords(List<String> dict, String sentence) {
        return sentence.replaceAll("\\b("+String.join("|", dict)+")\\w+", "$1");
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.