Java Regex Alternations Example

This Java regex example demonstrates how to use alternation operator | enables to create a regular expression with several choices.

Java Regex alternations

The alternation operator | enables to create a regular expression with several choices.
package net.javaguides.corejava.regex;

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

public class JavaRegexAlternation {

    public static void main(String[] args) {

        List < String > users = Arrays.asList("Ramesh", "Tom", "Tony",
            "Rocky", "John", "Prabhas");

        Pattern p = Pattern.compile("Ramesh|Tom|Prabhas|Rocky");

        for (String user: users) {

            Matcher m = p.matcher(user);

            if (m.matches()) {
                System.out.printf("%s -> matches%n", user);
            } else {
                System.out.printf("%s -> does not match%n", user);
            }
        }
    }
}
Output:
Ramesh -> matches
Tom -> matches
Tony -> does not match
Rocky -> matches
John -> does not match
Prabhas -> matches

References

Comments