Regular Expression Syntax

We said earlier that, within a pattern, all characters match themselves except for . | ( ) [ ] { } + \ ^ $ * and ?. Those characters all have special meanings in regular expression patterns. First, always remember that you need to escape any of these characters with a backslash if you want them to be treated as regular characters to match:

 show_regexp(​'yes | no'​, ​/\|/​) ​# => yes ->|<- no
 show_regexp(​'yes (no)'​, ​/\(no\)/​) ​# => yes ->(no)<-
 show_regexp(​'are you sure?'​, ​/e\?/​) ​# => are you sur->e?<-

Now let’s see what some of these characters mean if you use them without escaping them.

Anchors

By default, a regular expression will try to find the first match for the pattern in a string. Match /iss/ ...

Get Programming Ruby 3.3 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.