How to remove non ASCII characters from a string?

The code snippet below remove the characters from a string that is not inside the range of x20 and x7E ASCII code. The regex below strips non-printable and control characters. But it also keeps the linefeed character n (x0A) and the carriage return r (x0D) characters.

package org.kodejava.example.regex;

public class ReplaceNonAscii {
    public static void main(String[] args) {
        String str = "Thè quïck brøwn føx jumps over the lãzy dôg.";
        System.out.println("str = " + str);

        // Replace all non ascii chars in the string.
        str = str.replaceAll("[^\\x0A\\x0D\\x20-\\x7E]", "");
        System.out.println("str = " + str);
    }
}

Snippet output:

str = Thè quïck brøwn føx jumps over the lãzy dôg.
str = Th quck brwn fx jumps over the lzy dg.

How do I replace text in the JTextArea?

In this example you’ll see how to use the replaceRange(String str, int start, int end) method to replace a string in the JTextArea from the start position to the end position with the specified string.

package org.kodejava.example.swing;

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

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

    private void initializeUI() {
        String text = "The quick white fox jumps over the sleepy dog.";

        JTextArea textArea = new JTextArea(text);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        JScrollPane scrollPane = new JScrollPane(textArea);

        textArea.replaceRange("brown", 10, 15);
        textArea.replaceRange("lazy", 35, 41);

        this.setPreferredSize(new Dimension(500, 200));
        this.setLayout(new BorderLayout());
        this.add(scrollPane, BorderLayout.CENTER);
    }

    public static void showFrame() {
        JPanel panel = new TextAreaReplaceText();
        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(new Runnable() {
            public void run() {
                TextAreaReplaceText.showFrame();
            }
        });
    }
}

The screenshot of the code snippet above is:

JTextArea Replace Text Demo

How do I append and replace content of a StringBuffer?

A StringBuffer is like a String, but can be modified. StringBuffer are safe for use by multiple threads. The methods are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order that is consistent with the order of the method calls made by each of the individual threads involved.

As of release JDK 1.5, this class has been supplemented with an equivalent class designed for use by a single thread, StringBuilder. The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.

package org.kodejava.example.lang;

public class StringBufferAppendReplace {
    public static void main(String[] args) {
        StringBuffer quote = new StringBuffer("an apple ");
        char a = 'a';
        String day = " day";
        StringBuffer sentences = new StringBuffer(" keep the doctor away");

        // Append a character into StringBuffer
        quote.append(a);
        System.out.println("quote = " + quote.toString());

        // Append a string into StringBuffer
        quote.append(day);
        System.out.println("quote = " + quote.toString());

        // Append another StringBuffer
        quote.append(sentences);
        System.out.println("quote = " + quote.toString());

        // Replace a sub string from StringBuffer starting
        // from index = 3 to index = 8
        quote.replace(3, 8, "orange");
        System.out.println("quote = " + quote.toString());
    }
}

Here is our program output:

quote = an apple a
quote = an apple a day
quote = an apple a day keep the doctor away
quote = an orange a day keep the doctor away

How do I find and replace string?

The code below demonstrates the use Matcher.appendReplacement() and Matcher.appendTail() methods to create a program to find and replace a sub string within a string.

Another solution that can be used to search and replace a string can be found on the following example: How do I create a string search and replace using regex?.

package org.kodejava.example.regex;

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

public class AppendReplacementExample {
    public static void main(String[] args) {
        // Create a Pattern instance
        Pattern pattern = Pattern.compile("[Pp]en");

        // Create matcher object
        String input = "Please use your Pen to answer the question, " +
                "black pen is preferred.";
        Matcher matcher = pattern.matcher(input);
        StringBuffer sb = new StringBuffer();

        // Find and replace the text that match the pattern
        while (matcher.find()) {
            matcher.appendReplacement(sb, "pencil");
        }

        // This method reads characters from the input sequence, starting
        // at the append position, and appends them to the given string
        // buffer. It is intended to be invoked after one or more
        // invocations of the appendReplacement method in order to copy
        // the remainder of the input sequence.
        matcher.appendTail(sb);

        System.out.println("Input : " + input);
        System.out.println("Output: " + sb.toString());
    }
}

Here is the result of the above code:

Input : Please use your Pen to answer the question, black pen is preferred.
Output: Please use your pencil to answer the question, black pencil is preferred.

How do I create a string search and replace using regex?

In this example you’ll see how we can create a small search and replace program using the regular expression classes in Java. The code below will replace all the brown words to red.

package org.kodejava.example.regex;

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

public class StringReplace {
    public static void main(String[] args) {
        String source = "The quick brown fox jumps over the brown lazy dog.";
        String find = "brown";
        String replace = "red";

        // Compiles the given regular expression into a pattern.
        Pattern pattern = Pattern.compile(find);

        // Creates a matcher that will match the given input against the
        // pattern.
        Matcher matcher = pattern.matcher(source);

        // Replaces every subsequence of the input sequence that matches
        // the pattern with the given replacement string.
        String output = matcher.replaceAll(replace);

        System.out.println("Source = " + source);
        System.out.println("Output = " + output);
    }
}

The result of the code snippet is:

Source = The quick brown fox jumps over the brown lazy dog.
Output = The quick red fox jumps over the red lazy dog.

How do I replace characters in string?

package org.kodejava.example.lang;

public class StringReplace {
    public static void main(String[] args) {
        String text = "The quick brown fox jumps over the lazy dog";
        System.out.println("Before: " + text);

        // The replace method replace all occurrences of character
        // 'o' with 'u' and returns a new string object.
        text = text.replace('o', 'u');
        System.out.println("After : " + text);
    }
}

The result of the code snippet:

Before: The quick brown fox jumps over the lazy dog
After : The quick bruwn fux jumps uver the lazy dug