A Java method to replace all instances of a pattern in a String with a replacement pattern

Note: The code shown below is a bit old. If you want to perform a “search and replace” operation on all instances of a given pattern, all you have to do these days is use the replaceAll method on a Java String, like this:

String s = "123 Main Street";
String result = s.replaceAll("[0-9]", "-");

That second line of code returns the string “--- Main Street”. I kept the information below here for background information.

Older/background information

As a quick note today, here’s a Java method that will perform a “find and replace” operation on all instances of a given pattern:

private static String findAndReplaceAll(
    String pattern,
    String replaceWith, 
    String inputString)
{
    Pattern pattern = Pattern.compile(pattern);
    Matcher matcher = pattern.matcher(inputString);
    return matcher.replaceAll(replaceWith);
}

More accurately, that method replaces all instances of pattern that are found in inputString with the string replaceWith.

I call it like this to create a new string where all integers are replaced with a “-” character:

String result = findAndReplaceAll("[0-9]", "-", originalString);

I also call it like this to replace all tab characters with a single space:

String result = findAndReplaceAll("\t", " ", originalString);

In summary, if you were looking for a Java method to replace all instances of a pattern in a String with a replacement pattern, I hope this is helpful.

Share it!

There’s just one person behind this website; if this article was helpful (or interesting), I’d appreciate it if you’d share it. Thanks, Al.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.