Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

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

public class Main {
    public static void main(String[] args) {
        String regex = "\\b\\d+\\b";
        StringBuffer sb = new StringBuffer();
        String replacementText = "";
        String matchedText = "";

        String text = "We have 7 tutorials for Java, 2 tutorials for Javascript and 1 tutorial for Oracle.";

        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(text);

        while (m.find()) {
            matchedText = m.group();
            int num = Integer.parseInt(matchedText);
            if (num == 1) {
                replacementText = "only one";
            } else if (num < 5) {
                replacementText = "a few";
            } else {
                replacementText = "many";
            }
            m.appendReplacement(sb, replacementText);
        }

        m.appendTail(sb);
        System.out.println("Old  Text: " + text);
        System.out.println("New Text: " + sb.toString());
    }
}