| symbol defines an 'or' operation - Java Regular Expressions

Java examples for Regular Expressions:Pattern

Introduction

It lets you create patterns that accept any of two or more variations.

For example, here's an improvement to the pattern for validating droid names.

| character indicates that either the group on the left or the group on the right can be used to match the string.

The group on the left matches a word character, a digit, a hyphen, a word character, and another digit.

The group on the right matches a word character, a hyphen, a digit, and two word characters.

Demo Code

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

public class Main {
  public static void main(String[] args) {
    Pattern pattern = Pattern.compile("(\\w\\d-\\w\\d)|(\\w-\\d\\w\\w)");
    Matcher matcher = pattern.matcher("r2-d2");
    if (matcher.matches())
      System.out.println("Match.");
    else/*from  ww  w . j  a v a  2 s  .co  m*/
      System.out.println("Does not match.");
  }

}

Related Tutorials