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();
    scan.close();
    // replaces all special words by ***
    // b means we are looking for word boundaries
    String foo2 = foo.replaceAll(
      "\\b[a-z][0-9][0-9]\\b",
      "***"
    );
    System.out.println(foo2);
    }
}

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

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

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

Tags
comments powered by Disqus