Regular Expressions Basics

Marchete
8,279 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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.

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content