How do I write simple character class regex?

A character class in the context of regular expression is a set of characters enclosed within a square brackets "[]". It specifies the characters that will successfully match a single character from the given input.

A simple class, the most basic form of character class, is formed simply by placing a set of characters side-by-side within square brackets. For example the regular expression b[ai]t will match the words "bit" or "bat" because the pattern defines a character class accepting either "i" or "a" as the middle character.

package org.kodejava.regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CharacterClassesSimpleClassDemo {
    public static void main(String[] args) {
        // Creating a simple class type of character classes.
        // The regular expression below will search all sequences
        // of string that begins with 'b', ends with 't' and have
        // a middle letter of 'a' or 'i'.
        String regex = "b[ai]t";

        // Compiles the pattern and obtains the matcher object.
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher =
                pattern.matcher("I'm a little bit afraid of bats " +
                        "but not cats.");

        // Find every match and prints it.
        while (matcher.find()) {
            System.out.format("Text \"%s\" found at %d to %d.%n",
                    matcher.group(), matcher.start(), matcher.end());
        }
    }
}

The program will print the following output:

Text "bit" found at 13 to 16.
Text "bat" found at 27 to 30.

How do I set the tab size in JTextArea?

In this example you will be shown how to set or change the tab size for the JTextArea component. You can use the setTabSize(int size) to define the tab size. For this demo we create a combo box that have some integer values which will be used to define the tab size. When you change the selected item in the combo box the JTextArea tab size will be change immediately.

package org.kodejava.swing;

import javax.swing.*;
import java.awt.*;

public class TextAreaSetTabSize extends JPanel {
    public TextAreaSetTabSize() {
        initializeUI();
    }

    public static void showFrame() {
        JPanel panel = new TextAreaSetTabSize();
        panel.setOpaque(true);

        JFrame frame = new JFrame("JTextArea Demo");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(TextAreaSetTabSize::showFrame);
    }

    private void initializeUI() {
        this.setLayout(new BorderLayout());
        this.setPreferredSize(new Dimension(500, 200));

        JLabel label = new JLabel("Tab size: ");
        Object[] items = {2, 4, 8, 10, 20};
        final JComboBox<Object> comboBox = new JComboBox<>(items);

        JPanel tabPanel = new JPanel(new FlowLayout());
        tabPanel.add(label);
        tabPanel.add(comboBox);

        this.add(tabPanel, BorderLayout.NORTH);

        final JTextArea textArea = new JTextArea();
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);

        // Sets the number of characters to expand tabs to.
        textArea.setTabSize((Integer) comboBox.getSelectedItem());
        comboBox.addItemListener(e -> textArea.setTabSize(
                (Integer) comboBox.getSelectedItem()));

        JScrollPane pane = new JScrollPane(textArea);
        pane.setPreferredSize(new Dimension(500, 200));
        pane.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        this.add(pane, BorderLayout.CENTER);
    }
}

The output of the code snippet above is:

JTextArea Tab Size Demo

How do I set and get the contents of JTextArea?

To set and get the contents of a JTextArea you can use the setText(String text) and getText() methods. In the code below we create a JTextArea and sets its contents after we create a new instance of JTextArea. To get the contents we use the action on a button. When the button is pressed the contents of the JTextArea is read using the getText() method. This method return a String object.

package org.kodejava.swing;

import javax.swing.*;
import java.awt.*;

public class TextAreaGetContent extends JPanel {
    public TextAreaGetContent() {
        initializeUI();
    }

    public static void showFrame() {
        JPanel panel = new TextAreaGetContent();
        panel.setOpaque(true);

        JFrame frame = new JFrame("JTextArea Demo");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(TextAreaGetContent::showFrame);
    }

    private void initializeUI() {
        this.setLayout(new BorderLayout());
        this.setPreferredSize(new Dimension(500, 200));

        final JTextArea textArea = new JTextArea();

        // Set the contents of the JTextArea.
        String text = "The quick brown fox jumps over the lazy dog.";
        textArea.setText(text);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);

        JScrollPane pane = new JScrollPane(textArea);
        pane.setPreferredSize(new Dimension(500, 200));
        pane.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        JButton button = new JButton("Get Contents");
        button.addActionListener(e -> {
            // Get the contents of the JTextArea component.
            String contents = textArea.getText();
            System.out.println("contents = " + contents);
        });

        this.add(pane, BorderLayout.CENTER);
        this.add(button, BorderLayout.SOUTH);
    }
}

The output of the code snippet above is:

Set and Get the Content of JTextArea

How do I match a regex pattern in case-insensitive?

Finding the next subsequence of the input sequence that matches the pattern while ignoring the case of the string in regular expression can simply apply by create a pattern using compile(String regex, int flags) method and specifies a second argument with PATTERN.CASE_INSENSITIVE constant.

package org.kodejava.regex;

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class RegexIgnoreCaseDemo {
    public static void main(String[] args) {
        String sentence =
                "The quick brown fox and BROWN tiger jumps over the lazy dog";

        Pattern pattern = Pattern.compile("brown", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(sentence);

        while (matcher.find()) {
            System.out.format("Text \"%s\" found at %d to %d.%n",
                    matcher.group(), matcher.start(), matcher.end());
        }
    }
}

Here is the result of the program:

Text "brown" found at 10 to 15.
Text "BROWN" found at 24 to 29.

How do I wrap the text lines in JTextArea?

To wrap the lines of JTextArea we need to call the setLineWrap(boolean wrap) method and pass a true boolean value as the parameter. The setWrapStyleWord(boolean word) method wrap the lines at word boundaries when we set it to true.

package org.kodejava.swing;

import javax.swing.*;
import java.awt.*;

public class TextAreaWrapDemo extends JPanel {
    public TextAreaWrapDemo() {
        initializeUI();
    }

    public static void showFrame() {
        JPanel panel = new TextAreaWrapDemo();
        panel.setOpaque(true);

        JFrame frame = new JFrame("JTextArea Demo");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(TextAreaWrapDemo::showFrame);
    }

    private void initializeUI() {
        this.setLayout(new BorderLayout());
        this.setPreferredSize(new Dimension(500, 200));

        JTextArea textArea = new JTextArea(5, 40);

        String text = """
                The quick brown fox jumps over the lazy dog. \
                The quick brown fox jumps over the lazy dog. \
                The quick brown fox jumps over the lazy dog.
                """;

        textArea.setText(text);
        textArea.setFont(new Font("Arial", Font.BOLD, 18));

        // Wrap the lines of the JTextArea if it does not fit in the
        // current allocated with of the JTextArea.
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        JScrollPane scrollPane = new JScrollPane(textArea);

        this.add(scrollPane, BorderLayout.CENTER);
    }
}

The output of the code snippet above is:

JTextArea Wrap Text Line Demo