Hi, I'm Ataias Reis

Programmer, made in Brazil, Alma mater University of Brasilia

Replace regex matched substring by another substring in Java

The goal of this post is to show how to match words and replace them in a string using java. We are looking for words of three characters that start with a lower case letter and are followed by two digits. It took me a while to remember about the word boundaries (those represented by \\b). Pay attention to that. By the way, this exercise I found on the book Competitive Programming.

import java.util.*;

class Main {
  public static void main(String[] args) throws Exception{
    Scanner scan = new Scanner(System.in);
    String foo = scan.nextLine();
    // replaces all special words by ***
    // b means we are looking for word boundaries
    String foo2 = foo.replaceAll(

Compiling, running, giving an input and receiving an output:

$ javac string_replace.java
$ java Main
# input
a70 and z72, aa24 and a873
*** and ***, aa24 and a873

That's all for this post. Thanks for reading!

comments powered by Disqus