Back
Close

Regular Expressions Basics

Marchete
24.2K views

Alternations (|)

With [ ], you have the OR operator at a character level. With alternation, you have the OR operator at the pattern level:

(pattern1|pattern2|pattern3) will match either pattern1 OR pattern2 OR pattern3.

Those subpatterns can be as complex as needed, and there is no limit to the number of patterns that can be separated by the | metacharacter.

Examples:

  • Example 1: (yes|no) Will search for exactly yes OR no.
  • Example 2: ([Yy]es|[Nn]o){2,4} Will search for Yes OR yes OR No OR no repeated between two to four times.
  • Example 3: \b([0-9]+|[a-z]+)\b Will search for a word made entirely of digits OR a word made entirely of lowercase letters. But it won't match mixtures of letters and digits.
  • Example 4: (([Yy]es|[Nn]o){2,4}|\b([0-9]+|[a-z]+)\b) Combination of the two previous patterns. So it matches either the same as "Example 2" OR "Example 3".
Exercise 5 - Search Image Files
namespace RegexCourse{
public static class Exercise5{
//Search image files.
//Files are composed as follows:
//"filename.extension"
//"filename" is formed as one or more of the following characters:
// -Any alphanumeric character (a to z, and 0 to 9)
// -Any of these symbols: .+-_=()
//Valid "extension" for images are:
// jpg,jpeg,png,bmp,gif
//The filesystem is case insensitive, so name and extension can be on any case.
public static string Pattern_Exercise5=@"";
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Continue to the next lesson to learn about Groups and Capturing Groups.

Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants