O'Reilly logo

Learning Rails: Live Edition by Edd Dumbill, Simon St. Laurent

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Sequences, Repetition, Groups, and Choices

Specifying a simple match pattern may take care of most of what you need regular expressions for use in Rails, but there are a few additional pieces you should know about before moving on. Even if you don’t match something that needs these, knowing what they look like will help you read other regular expressions when you encounter them.

There are three classic symbols that indicate whether an item is optional or can repeat, plus a notation that lets you specify how much something should repeat, as shown in Table C-5.

Table C-5. Options and repetition

Syntax

Meaning

?

The pattern right before it should appear 0 or 1 times.

*

The pattern right before it should appear 0 or more times.

+

The pattern right before it should appear 1 or more times.

{number}

The pattern before the opening curly brace should appear exactly number times.

{number,}

The pattern before the opening curly brace should appear at least number times.

{number1, number2}

The pattern before the opening curly brace should appear at least number1 times but no more than number2 times.

You might think you’re ready to go create expressions armed with this knowledge, but you’ll find some unpleasant surprises. The regular expression:

/1998+/

might look like it will match one or more instances of “1998”, but it will actually match “199” followed by one or more instances of “8”. To make it match a sequence of 1998s, you would write:

/(1998)+/

If you wanted to specify, say, two to five occurrences ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required