Start learning free

LESSON 619 OF 671 · PROJECTS: COMMAND-LINE TOOLS

grep -w in Java: Whole-Word Match with Regex Word Boundaries

Practice Read the full explanation

Build the -w flag of the Unix grep command. Given a list of lines and a search pattern (a single word made of letters, digits, and underscores), return all lines that contain pattern as a WHOLE word — i.e. the characters immediately before and after the match must NOT be word characters (letters, digits, or underscores). The match is case-sensitive.

Return the matching lines joined by newline characters (\n).

Function signature:

public String grepWord(List<String> lines, String pattern)

Example:

Input:
pattern = "cat"
lines = ["cat sat", "concat", "the cat", "category"]

Output: "cat sat\nthe cat"

When printed:
cat sat
the cat

Notice that "concat" is rejected because cat is preceded by the word character n (con|cat), and "category" is rejected because cat is followed by the word character e.

A line may contain the pattern more than once. It is selected if at least one occurrence is a whole word: with pattern "cat", the line "concat cat" is selected because of its second cat. The lines contain only ASCII characters.

If no lines match, return the empty string "".


Use java.util.regex.Pattern with \b word-boundary anchors. Wrap the pattern itself with Pattern.quote to escape any regex metacharacters.

java.util.regex.Pattern regex = java.util.regex.Pattern.compile(
    "\\b" + java.util.regex.Pattern.quote(pattern) + "\\b"
);
// per line: if (regex.matcher(line).find()) keep


The full solution:
class Solution {
    public String grepWord(List<String> lines, String pattern) {
        List<String> result = new ArrayList<>();
        java.util.regex.Pattern regex = java.util.regex.Pattern.compile(
            "\\b" + java.util.regex.Pattern.quote(pattern) + "\\b"
        );
        for (String line : lines) {
            if (regex.matcher(line).find()) {
                result.add(line);
            }
        }
        return String.join("\n", result);
    }
}

STEP 1 OF 6
    Ctrl + Enter to check

    JAVA · PROJECTS: COMMAND-LINE TOOLS

    Grep V4 in Java, explained

    Problem overview

    The method grepWord takes a List<String> named lines and a pattern, a single word made of letters, digits and underscores. It returns the lines that contain the pattern as a whole word, joined by newline characters. A whole word means the character just before the match and the character just after it must not be word characters (letters, digits or underscores). The match is case-sensitive, and the lines contain only ASCII characters. If nothing matches, the result is "".

    For pattern = "cat" and lines = ["cat sat", "concat", "the cat", "category"] the result is "cat sat\nthe cat". "concat" is rejected because the cat inside it is preceded by n, and "category" is rejected because it is followed by e. A line is selected if at least one occurrence is a whole word, so "concat cat" is selected because of its second cat.

    Approach: a regular expression with word boundaries

    Plain contains would accept "concat", so the check needs to look at the neighbours of a match. Doing that by hand means finding every occurrence, inspecting the characters on both sides, and moving on to the next occurrence when the first one fails. A regular expression does all of that in one pattern.

    In a regex, \b is a word boundary: a position between a word character and a non-word character, or between a word character and the start or end of the text. Wrapping the word in boundaries, \bcat\b, matches cat only where it stands alone. The regex finds the first such place anywhere in the line, and a line with several candidates is checked against all of them.

    The pattern text must be treated literally, though. If it were pasted into the regex as it is, a character with a special meaning in regular expressions would change what is matched. Pattern.quote wraps the text so that every character in it counts as itself.

    Step by step

    1. Create result, an empty ArrayList held in a List<String> variable.
    2. Build the regex once, before the loop, with Pattern.compile and keep it in a Pattern named regex. The text is "\\b", then Pattern.quote(pattern), then "\\b" again. In a Java string literal each backslash is written twice. The class is written as java.util.regex.Pattern.
    3. Loop over the lines with a for-each loop naming each entry line.
    4. Search each line. regex.matcher(line) creates a matcher for that line, and find() returns true if the regex matches anywhere in it. One whole-word match is enough to keep the line.
    5. Keep the line with result.add(line).
    6. Join and return with String.join("\n", result); with no matches this gives "".

    The solution in Java

    class Solution {
        public String grepWord(List<String> lines, String pattern) {
            List<String> result = new ArrayList<>();
            java.util.regex.Pattern regex = java.util.regex.Pattern.compile("\\b" + java.util.regex.Pattern.quote(pattern) + "\\b");
            for (String line : lines) {
                if (regex.matcher(line).find()) {
                    result.add(line);
                }
            }
            return String.join("\n", result);
        }
    }
    

    The Java details worth a closer look:

    • Two Patterns. The parameter pattern is a String, the text to look for. The variable regex is a java.util.regex.Pattern, the compiled expression. They are different things with confusingly similar names. The fully qualified class name saves an import; with import java.util.regex.Pattern; the code could say just Pattern.
    • Why \\b. The regex is \b. Inside a Java string a backslash begins an escape sequence, so it is doubled. A single "\b" in Java source is a backspace character, which is a different thing entirely.
    • Why Pattern.quote. It surrounds the text with \Q...\E, which switches off special meaning. The lesson's patterns are plain words, but without quoting, a pattern like c.t would be read as "c, any character, t". Compiled without quote, the regex \bc.t\b finds a match in "cut"; compiled with it, it does not.
    • find() against matches(). find() looks for a match anywhere in the text. matches() succeeds only if the regex matches the entire line, so it would reject "the cat".
    • Compiling once. Building a regex is more expensive than using it, so it is compiled before the loop and reused for every line.
    • Imports. List and ArrayList need import java.util.*; in a standalone file.

    Complexity

    Let n be the number of lines and m the total number of characters in them.

    Time: O(m * p) in the worst case, with p as the length of the pattern. The matcher tries each position in each line, and a try compares at most the pattern's characters. Compiling the regex costs O(p) once.

    Space: O(n + m), for the result list and the joined string, plus the compiled regex.

    Edge cases and common mistakes

    • Underscores and digits are word characters. With the pattern "cat", the lines "cat_x" and "cat1" are rejected, while "cat-x", "cat." and "(cat)" are accepted, as is a line that is just "cat".
    • Case matters. ["Cat", "cat"] with "cat" gives "cat".
    • The word at the start or end of the line. \b also matches at the edges of the text, so "cat sat" and "the cat" both match.
    • No match. An empty list, a list holding one empty line, and a list with no whole word all give "".
    • Using contains. It accepts "concat" and "category".
    • Forgetting the doubled backslash. "\b" + ... compiles in Java, but the string holds a backspace character and no line matches.
    • A dot in the pattern. With the pattern "a.b", quoting means ["a.b", "axb"] returns only "a.b".

    Testing

    • ["cat sat", "concat", "the cat", "category"] with "cat" gives "cat sat\nthe cat".
    • ["concat cat"] with "cat" gives "concat cat".
    • ["cat_x", "cat1", "cat-x", "cat.", "(cat)", "cat"] with "cat" gives "cat-x\ncat.\n(cat)\ncat".
    • ["Cat", "cat"] with "cat" gives "cat".
    • [] with "cat" gives "".
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free