String Formatting and Regular Expressions

What we’ll cover

Formatting Strings

Built-in Formatting Utilities

Formatting: String Formatting

Format specifiers

Formatting: String Formatting
Example 1

public void demo() {
  String formattedString = "Hey! [ %s ] is my name!";
  String arg1 = "Leon";
  String outputString = String.format(formattedString, arg1);
  System.out.println(outputString);
}

Output

Hey! [ Leon ] is my name!

Formatting: String Formatting
Example 2

public void demo() {
  String formattedString = "I am %d years old.";
  Integer arg1 = 25;
  String outputString = String.format(formattedString, arg1);
  System.out.println(outputString);
}

Output

I am 25 years old.

Formatting: String Formatting
Example

public void demo() {
  String formattedString = "I've finished %.5f percent of homework";
  Double arg1 = 79.87654321;
  String outputString = String.format(formattedString, arg1);
  System.out.println(outputString);
}

Output

I've finished 79.87654 percent of homework

Formatting: String Formatting
Example

public void demo() {
  String formattedString = "I've finished %.3f percent of homework";
  Double arg1 = 79.87654321;
  String outputString = String.format(formattedString, arg1);
  System.out.println(outputString);
}

Output

I've finished 79.876 percent of homework

Formatting: String Formatting
Example

public void demo() {
  String formattedString = "I've finished %.2f percent of homework";
  Double arg1 = 79.87654321;
  String outputString = String.format(formattedString, arg1);
  System.out.println(outputString);
}

Output

I've finished 79.87 percent of homework

Formatting: String Formatting
Example

public void demo() {
  Integer precision1 = 4;
  Integer precision2 = 5;
  Double valueToFormat = 79.87654321;
  String output1 = getHomeworkDetails(precision1, valueToFormat);
  String output2 = getHomeworkDetails(precision2, valueToFormat);
  System.out.println(output1);
  System.out.println(output2);
}
public String getHomeworkDetails(Integer decimalPrecision, Double valueToFormat) {
  String formattedString = new StringBuilder("I've finished %.")
    .append(decimalPrecision)
    .append("f percent of homework")
    .toString();
  return String.format(formattedString, valueToFormat);
}

Output

I've finished 79.8765 percent of homework
I've finished 79.87654 percent of homework

Formatting: String Formatting
Example

public void demo() {
  String formattedString = "My first initial is %c.";
  Character arg1 = 'J';
  String outputString = String.format(formattedString, arg1);
  System.out.println(outputString);
}

Output

My first initial is J.

Formatting: String Formatting
Example

public void demo() {
  String formattedString = "Hey! My name is %s. I am %d years old.";
  String arg1 = "Leon";
  Integer arg2 = 25;
  String outputString = String.format(formattedString, arg1, arg2);
  System.out.println(outputString);
}

Output

Hey! My name is Leon. I am 25 years old.

Formatting: System OutputStream

Formatting: System OutputStream
Example 1

public void demo() {
  String formattedString = "Hey! [ %s ] is my name!";
  String arg1 = "Leon";
  System.out.format(formattedString, arg1);
}

Output

Hey! [ Leon ] is my name!

Formatting: System OutputStream
Example 2

public void demo() {
  String formattedString = "I am %d years old.";
  Integer arg1 = 25;
  System.out.format(formattedString, arg1);
}

Output

I am 25 years old.

Formatting: System OutputStream
Example 3

public void demo() {
  String formattedString = "Hey! My name is %s. I am %d years old.";
  String arg1 = "Leon";
  Integer arg2 = 25;
  System.out.format(formattedString, arg1, arg2);
}

Output

Hey! My name is Leon. I am 25 years old.

Formatting: Formatter Class

Formatting: Formatter
Example 1

public void demo() {
  String fileName = "MyFile.txt";
  String formattedString = "Hi, my name is %s!";
  String arg1 = "Leon";

  FileOutputStream outputStream = new FileOutputStream(fileName);
  Formatter formatter = new Formatter(outputStream);
  formatter.format(formattedString, arg1);
  formatter.flush();
}

Output: MyFile.txt content

Hi, my name is Leon!

Formatting: Formatter
Example 2

public void demo() {
  String fileName = "MyFile.txt";
  String formattedString = "Hi, my age is %d!";
  Integer arg1 = 25;

  FileOutputStream outputStream = new FileOutputStream(fileName);
  Formatter formatter = new Formatter(outputStream);
  formatter.format(formattedString, arg1);
  formatter.flush();
}

Output: MyFile.txt content

Hi, my age is 25!

Formatting: Formatter
Example 3

public void demo() {
  String fileName = "MyFile.txt";
  String formattedString = "Hi, my age is %.1f!";
  Double arg1 = 25.2;

  FileOutputStream outputStream = new FileOutputStream(fileName);
  Formatter formatter = new Formatter(outputStream);
  formatter.format(formattedString, arg1);
  formatter.flush();
}

Output: MyFile.txt content

Hi, my age is 25.2!

##Reminder re: FileOutputStream When using FileOutputStream, you will need to either add a FileNotFoundException or use a try/catch block

Regular expressions

Character classes

Expression Description
`.` any character except newline
`\w`, `\d`, `\s` word / digit / whitespace
`\W`, `\D`, `\S` not word / not digit / not whitespace
`[abc]` any of `a`, `b`, or `c`
`[^abc]` not `a`, not `b`, not `c`
`[a-g]` character between `a` and `g`

Using Character Classes

public void demo() {
    String text = "The Quick Brown Fox";
    String patternString = ".";
    Pattern pattern = Pattern.compile(patternString);
    Matcher matcher = pattern.matcher(text);
    for (int i = 0; matcher.find(); i++) {
        System.out.println(new StringBuilder()
                .append("\n-------------------")
                .append("\nValue = " + matcher.group())
                .append("\nMatch Number = " + i)
                .append("\nStarting index = " + matcher.start())
                .append("\nEnding index = " + matcher.end())
                .toString());

    }
}

Using Character Classes

Value = T
Match Number = 0
Starting index = 0
Ending index = 1

------------------
Value = h
Match Number = 1
Starting index = 1
Ending index = 2

------------------
Value = e
Match Number = 2
Starting index = 2
Ending index = 3

Anchors

Expression Description
`^abc$` start / end of the string
`\b`, `\B` word, digit, whitespace

Using Anchors

public void demo() {
    String text = "The Quick Brown";
    String patternString = "^The";
    Pattern pattern = Pattern.compile(patternString);
    Matcher matcher = pattern.matcher(text);
    for (int i = 0; matcher.find(); i++) {
        System.out.println(new StringBuilder()
                .append("\n-------------------")
                .append("\nValue = " + matcher.group())
                .append("\nMatch Number = " + i)
                .append("\nStarting index = " + matcher.start())
                .append("\nEnding index = " + matcher.end())
                .toString());
    }
}

Using Anchors

------------------
Value = The
Match Number = 0
Starting index = 0
Ending index = 3

Using Anchors

public void demo() {
    String text = "The Quick Brown";
    String patternString = "^Brown";
    Pattern pattern = Pattern.compile(patternString);
    Matcher matcher = pattern.matcher(text);
    for (int i = 0; matcher.find(); i++) {
        System.out.println(new StringBuilder()
                .append("\n-------------------")
                .append("\nValue = " + matcher.group())
                .append("\nMatch Number = " + i)
                .append("\nStarting index = " + matcher.start())
                .append("\nEnding index = " + matcher.end())
                .toString());
    }
}

Using Anchors

Escaped characters

Expression Description
`(abc)` capture group
`\1` backreference to group #1
`(?:abc)` non-capturing group
`(?=abc)` positive lookahead
`(?!abc)` negative lookahead

Using Escaped Characters

public void demo() {
    String text = "The Quick Brown";
    String patternString = "(Brown)";
    Pattern pattern = Pattern.compile(patternString);
    Matcher matcher = pattern.matcher(text);
    for (int i = 0; matcher.find(); i++) {
        System.out.println(new StringBuilder()
                .append("\n-------------------")
                .append("\nValue = " + matcher.group())
                .append("\nMatch Number = " + i)
                .append("\nStarting index = " + matcher.start())
                .append("\nEnding index = " + matcher.end())
                .toString());
    }
}

Using Escaped Characters

------------------
Value = Brown
Match Number = 0
Starting index = 10
Ending index = 15

Quantifies and Alternation

Expression Description
`a*`, `a+`, `a?` 0 or more, 1 or more, 0 or 1
`a{5}`, `a{2, }` exactly five, two or more
`a{1,3}` between one & three
`a+? a{2,}?` match as few as possible

Using Quantifies and Alternation

public void demo() {
    String text = "The Quick Brown";
    String patternString = "\\w+";
    Pattern pattern = Pattern.compile(patternString);
    Matcher matcher = pattern.matcher(text);
    for (int i = 0; matcher.find(); i++) {
        System.out.println(new StringBuilder()
                .append("\n-------------------")
                .append("\nValue = " + matcher.group())
                .append("\nMatch Number = " + i)
                .append("\nStarting index = " + matcher.start())
                .append("\nEnding index = " + matcher.end())
                .toString());
    }
}

Using Quantifies and Alternation

Value = The
Match Number = 0
Starting index = 0
Ending index = 3

------------------
Value = Quick
Match Number = 1
Starting index = 4
Ending index = 9

------------------
Value = Brown
Match Number = 2
Starting index = 10
Ending index = 15

More about regex symbols

More regex examples

Site for testing regex