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. |
| The pattern before the opening curly brace should appear exactly
|
| The pattern before the opening curly brace should appear at least
|
| The pattern before the opening curly brace should appear at least
|
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, ...
Get Learning Rails: Live Edition 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.