📢 Too many exams? Don’t know which one suits you best? Book Your Free Expert 👉 call Now!


    Question

    Complete the Java code to replace all occurrences of a

    specific word (case-insensitive) in a string. public class RegexReplacer {     public String replaceWord(String text, String wordToReplace, String replacement) {         // Example: text="Hello World", wordToReplace="world", replacement="Java"         // Expected: "Hello Java"         String regex = "(?i)\\b" + Pattern.quote(wordToReplace) + "\\b";         _________ // Line to complete     } }
    A return text.replaceAll(regex, replacement); Correct Answer Incorrect Answer
    B return text.replace(regex, replacement); Correct Answer Incorrect Answer
    C return text.replaceFirst(regex, replacement); Correct Answer Incorrect Answer
    D Pattern.compile(regex).matcher(text).replaceFirst(replacement); Correct Answer Incorrect Answer
    E return Pattern.compile(regex).matcher(text).replaceAll(replacement); Correct Answer Incorrect Answer

    Solution

    Correct Answer: E (The replaceAll method of Matcher is needed to replace all occurrences using a regex pattern. text.replaceAll is a convenience method that internally uses Pattern.compile and Matcher.replaceAll.)

    Practice Next
    More IT Operating System Questions
    ask-question