Some basic regular expression examples

Let's look at some basic examples of regular expressions:

    ab*c

This will match a, followed by zero or more b, followed by c.

    ab+c

This will match a followed by one or more b, followed by c.

    ab?c

This will match a followed by zero or one b, followed by c. Thus, it will match both abc or ac.

    ^abc$

This will match abc in a line, and the line must not have anything other than the string abc due to the use of the start and end anchors on either side of the regex.

    a(bc)*z

This will match a, followed by zero or more occurrences of the string bc, followed by z. Thus, it will match the following strings: az, abcz, abcbcz, abcbcbcz, and so on.

    ab{1,3}c

This will match a, followed by one to three occurrences ...

Get Java 9 Regular Expressions now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.