GNGiseldo Neo and Alana NeoBooks
Introduction to Programming in Java19 / 25

Text Processing with Regular Expressions

Extracting meaning from free text

18.1 Learning Objectives

By the end of this chapter, you should be able to:

  • use regular expressions to identify patterns in text;
  • extract key phrases from user messages;
  • apply grammatical transformations to build responses;
  • integrate regular expressions into a chatbot to create smarter replies;
  • understand the core mechanism behind ELIZA.

18.2 Introduction to Text Processing

Text processing: from raw message to smart response.

Figure 18.1. Text processing: from raw message to smart response.

What makes a chatbot like ELIZA special is its ability to:

  1. Identify patterns in the user’s text
  2. Extract key phrases that matter for the reply
  3. Grammatically transform those phrases to produce coherent responses

For example, when a user says "I want a coffee", a smart chatbot can reply "Why do you want a coffee?" or "What would it mean to you if you got a coffee?".

18.3 Regular Expressions in Java

Java provides the Pattern and Matcher classes in the java.util.regex package for working with regular expressions.

18.3.1 Basic Regex Concepts

SymbolMeaningExample
.Any charactera.c matches "abc", "aXc", "a c"
*Zero or more occurrencesab*c matches "ac", "abc", "abbc"
+One or more occurrencesab+c matches "abc", "abbc" (not "ac")
?Zero or one occurrenceab?c matches "ac", "abc"
[]Character set[aeiou] matches any vowel
``OR
()Capture group(ab)+ matches "ab", "abab", "ababab"
^Start of string^Hello matches "Hello world"
$End of stringworld$ matches "Hello world"
\\dDigit\\d+ matches "123", "45"
\\wWord character\\w+ matches "hello", "test123"
\\sWhitespace\\s+ matches " ", " "

18.3.2 Example 1: Checking Simple Patterns

Complete source in BasicRegex.java:

import java.util.regex.*;

public class BasicRegex {
    public static void main(String[] args) {
        String text = "I want to learn Java";

        // Checks whether the text contains "Java"
        Pattern pattern = Pattern.compile("Java");
        Matcher matcher = pattern.matcher(text);

        System.out.println("Contains 'Java': " + matcher.find());

        // Checks whether the text starts with "I"
        pattern = Pattern.compile("^I");
        matcher = pattern.matcher(text);
        System.out.println("Starts with 'I': " + matcher.find());

        // Checks whether the text ends with "Java"
        pattern = Pattern.compile("Java$");
        matcher = pattern.matcher(text);
        System.out.println("Ends with 'Java': " + matcher.find());
    }
}

18.4 Extracting Key Phrases

ELIZA’s technique relies on recognizing sentence patterns and extracting key parts of the user’s message so they can be woven back into the reply.

18.4.1 Example 2: Extraction with Capture Groups

Complete source in PhraseExtraction.java:

import java.util.regex.*;

public class PhraseExtraction {

    private static final String BOT_TEMPLATE = "BOT: %s";
    private static final String USER_TEMPLATE = "USER: %s";

    public static void main(String[] args) {
        String message = "I want to learn how to build chatbots";

        // Pattern to capture what the user wants
        Pattern pattern = Pattern.compile("I want (.*)");
        Matcher matcher = pattern.matcher(message);

        if (matcher.find()) {
            String phrase = matcher.group(1); // "to learn how to build chatbots"
            System.out.println(String.format(USER_TEMPLATE, message));
            System.out.println(String.format(BOT_TEMPLATE, "Why do you want " + phrase + "?"));
        }

        // Test with another message
        message = "Do you remember the last time we coded together?";
        pattern = Pattern.compile("Do you remember (.*?)\\??$");
        matcher = pattern.matcher(message);

        if (matcher.find()) {
            String phrase = matcher.group(1);
            System.out.println(String.format(USER_TEMPLATE, message));
            System.out.println(String.format(BOT_TEMPLATE, "How could I forget " + phrase + "?"));
        }
    }
}

18.4.2 Example 3: Multiple Patterns

Let’s create a map of patterns and response templates, similar to ELIZA:

import java.util.*;
import java.util.regex.*;

public class ElizaRegex {
    private static final String BOT_TEMPLATE = "BOT: %s";
    private static final String USER_TEMPLATE = "USER: %s";

    // Map of regex patterns and possible responses
    private static final Map<Pattern, List<String>> RULES = new LinkedHashMap<>();
    private static final Random RANDOM = new Random();

    static {
        // Pattern for sentences like "I want X"
        RULES.put(Pattern.compile("I want (.*)", Pattern.CASE_INSENSITIVE), Arrays.asList(
            "What would it mean to you if you got {0}?",
            "Why do you want {0}?",
            "What is stopping you from getting {0}?"
        ));

        // Pattern for sentences like "Do you remember X"
        RULES.put(Pattern.compile("Do you remember (.*?)\\??$", Pattern.CASE_INSENSITIVE), Arrays.asList(
            "How could I forget {0}?",
            "Why wouldn't you be able to forget {0}?",
            "What is so special about {0}?"
        ));

        // Pattern for sentences like "If X"
        RULES.put(Pattern.compile("If (.*)", Pattern.CASE_INSENSITIVE), Arrays.asList(
            "Do you think it's likely that {0}?",
            "Do you wish that {0}?",
            "What do you think about {0}?",
            "Really... if {0}"
        ));
    }

    public static String matchRule(String message) {
        for (Map.Entry<Pattern, List<String>> entry : RULES.entrySet()) {
            Pattern pattern = entry.getKey();
            Matcher matcher = pattern.matcher(message);

            if (matcher.find()) {
                // Extracts the phrase from capture group 1
                String phrase = matcher.group(1);

                // Picks a random response
                List<String> responses = entry.getValue();
                String response = responses.get(RANDOM.nextInt(responses.size()));

                // Replaces {0} with the extracted phrase
                return response.replace("{0}", phrase);
            }
        }

        // Default response if no pattern matched
        return "That's interesting. Tell me more.";
    }

    public static void sendMessage(String message) {
        System.out.println(String.format(USER_TEMPLATE, message));
        String response = matchRule(message);
        System.out.println(String.format(BOT_TEMPLATE, response));
    }

    public static void main(String[] args) {
        sendMessage("I want to learn programming");
        sendMessage("Do you remember our last class?");
        sendMessage("If I study hard, I will pass");
        sendMessage("Hello, how are you?");
    }
}

18.5 Grammatical Transformation: Handling Pronouns

One of ELIZA’s secrets is swapping pronouns so replies sound much more natural. For example:

  • User: "I hate Java"

  • Bot: "Why do you hate Java?" (instead of "Why do I hate Java?")

  • User: "You like programming"

  • Bot: "What makes you think I like programming?" (instead of "What makes I think you like programming?")

18.5.1 Example 4: Pronoun Replacement Method

Notice that we perform all replacements in a single pass using Matcher.replaceAll(match -> ...) and a lookup map. If we replaced "i" with "you" first and then replaced "you" with "I" in a separate pass, the newly converted "you" would be turned right back into "I"!

Complete source in PronounReplacer.java:

import java.util.Map;
import java.util.regex.*;

public class PronounReplacer {

    private static final Map<String, String> PRONOUN_MAP = Map.of(
        "i", "you",
        "me", "you",
        "my", "your",
        "am", "are",
        "you", "I",
        "your", "my",
        "are", "am"
    );

    private static final Pattern PRONOUN_PATTERN =
        Pattern.compile("\\b(i|me|my|am|you|your|are)\\b");

    public static String replacePronouns(String phrase) {
        // Convert to lowercase to simplify matching
        String lowerPhrase = phrase.toLowerCase();
        Matcher matcher = PRONOUN_PATTERN.matcher(lowerPhrase);
        return matcher.replaceAll(match -> PRONOUN_MAP.get(match.group(1)));
    }

    public static void main(String[] args) {
        System.out.println(replacePronouns("I want my coffee"));   // "you want your coffee"
        System.out.println(replacePronouns("You have your pen"));  // "I have my pen"
        System.out.println(replacePronouns("My mom is nice"));     // "your mom is nice"
        System.out.println(replacePronouns("I am learning Java")); // "you are learning java"
    }
}

18.5.2 Example 5: Integrating Extraction and Transformation

Now let’s combine phrase extraction with pronoun transformation (complete source in FullEliza.java):

import java.util.*;
import java.util.regex.*;

public class FullEliza {
    private static final String BOT_TEMPLATE = "BOT: %s";
    private static final String USER_TEMPLATE = "USER: %s";

    private static final Map<Pattern, List<String>> RULES = new LinkedHashMap<>();
    private static final Random RANDOM = new Random();

    private static final Map<String, String> PRONOUN_MAP = Map.of(
        "i", "you",
        "me", "you",
        "my", "your",
        "am", "are",
        "you", "I",
        "your", "my",
        "are", "am"
    );

    private static final Pattern PRONOUN_PATTERN =
        Pattern.compile("\\b(i|me|my|am|you|your|are)\\b");

    static {
        RULES.put(Pattern.compile("I want (.*)", Pattern.CASE_INSENSITIVE), Arrays.asList(
            "What would it mean to you if you got {0}?",
            "Why do you want {0}?",
            "What is stopping you from getting {0}?"
        ));

        RULES.put(Pattern.compile("I (.*) you", Pattern.CASE_INSENSITIVE), Arrays.asList(
            "Why do you {0} me?",
            "What makes you feel that you {0} me?"
        ));

        RULES.put(Pattern.compile("Do you remember (.*?)\\??$", Pattern.CASE_INSENSITIVE), Arrays.asList(
            "How could I forget {0}?",
            "Why wouldn't you be able to forget {0}?"
        ));

        RULES.put(Pattern.compile("(?:Do you|You) (.*) me\\??$", Pattern.CASE_INSENSITIVE), Arrays.asList(
            "Why do you think I {0} you?",
            "What makes you think I {0} you?"
        ));
    }

    public static String replacePronouns(String phrase) {
        String lowerPhrase = phrase.toLowerCase();
        return PRONOUN_PATTERN.matcher(lowerPhrase)
            .replaceAll(match -> PRONOUN_MAP.get(match.group(1)));
    }

    public static String matchRule(String message) {
        for (Map.Entry<Pattern, List<String>> entry : RULES.entrySet()) {
            Pattern pattern = entry.getKey();
            Matcher matcher = pattern.matcher(message);

            if (matcher.find()) {
                String phrase = matcher.group(1);
                List<String> responses = entry.getValue();
                String response = responses.get(RANDOM.nextInt(responses.size()));

                // Apply pronoun transformation to the extracted phrase
                String transformedPhrase = replacePronouns(phrase);

                return response.replace("{0}", transformedPhrase);
            }
        }

        return "That's interesting. Tell me more.";
    }

    public static void sendMessage(String message) {
        System.out.println(String.format(USER_TEMPLATE, message));
        String response = matchRule(message);
        System.out.println(String.format(BOT_TEMPLATE, response));
    }

    public static void main(String[] args) {
        sendMessage("I want to learn Java");
        sendMessage("I hate you");
        sendMessage("Do you hate me?");
        sendMessage("Do you remember our last meeting?");
    }
}

18.6 Standardizing Input Processing

To make our chatbot more robust, let’s standardize how incoming messages are processed:

  1. Normalize letter case (convert to lowercase)
  2. Remove unnecessary punctuation
  3. Apply regular expression rules
  4. Transform pronouns

18.6.1 Example 6: Input Normalization

public class InputNormalizer {

    public static String normalize(String message) {
        // Convert to lowercase
        message = message.toLowerCase();

        // Remove punctuation except ? and !
        // Keep only letters, digits, whitespace, ?, !, and apostrophes
        message = message.replaceAll("[^a-zA-Z0-9\\s?!']", "");

        // Collapse multiple spaces into a single space
        message = message.replaceAll("\\s+", " ");

        // Remove leading and trailing whitespace
        return message.trim();
    }

    public static void main(String[] args) {
        System.out.println(normalize("Hello, how are you?"));         // "hello how are you?"
        System.out.println(normalize("  I   WANT   JAVA!  "));        // "i want java!"
        System.out.println(normalize("Learning... to program!!!"));   // "learning to program!!!"
    }
}

18.7 Project Evolution: Regex-Powered Chatbot

In this chapter, we added:

  1. Regular expressions to identify patterns in text
  2. Phrase extraction to capture key parts of a message
  3. Pronoun transformation to generate more natural replies
  4. Input normalization to handle variations in user typing

These capabilities form the foundation for a smarter chatbot that can:

  • Understand user intentions (intents)
  • Extract specific pieces of information (entities)
  • Generate contextually relevant responses

18.8 Verifiable Practice

  1. Implement a BasicRegex class that checks whether a string matches specific patterns.
  2. Create a PhraseExtraction class that extracts phrases using capture groups.
  3. Build the PronounReplacer class with pronoun substitution.
  4. Integrate everything into a FullEliza class that processes complete messages.
  5. Test with at least 15 different messages.

Completion criteria:

  • All examples compile with javac --release 21
  • Regex patterns accurately match the target phrases
  • Pronoun transformation works across all combinations
  • Input normalization handles punctuation and extra whitespace properly
  • The code follows Java naming conventions

Before moving on

You should be able to explain:

  • How do you use Pattern and Matcher to identify text patterns?
  • How do you extract phrases using capture groups?
  • How do you apply pronoun transformations to chatbot responses?
  • How do you normalize user input?
  • What is the core mechanism behind ELIZA?

18.9 Additional Resources