shou2017.com
JP

Regular Expressions in Ruby Silver Exam

Thu Jun 28, 2018
Sat Aug 10, 2024

Here are some notes on regular expressions that frequently appear in the Ruby Silver exam.

The reference used is this book. The following examples focus on regular expressions that appeared in the practice problems and mock exams of this study guide.

Revised 2nd Edition: Ruby Certification Exam Study Guide (Silver/Gold)

Surprisingly, there are only four questions on regular expressions. However, since they are guaranteed to appear, it’s important to understand them.

Below are actual questions from the Revised 2nd Edition: Ruby Certification Exam Study Guide (Silver/Gold).

Key Regular Expression Metacharacters

Metacharacter Meaning
[] Creates a character class to match any one character
[^] Creates a character class to match any one character except those specified
- Represents a range of characters when used inside []
. Matches any single character
() Captures or groups matched strings
? Matches the preceding character or pattern 0 or 1 time
* Matches the preceding character or pattern 0 or more times
+ Matches the preceding character or pattern 1 or more times
{n,m} Matches the preceding character or pattern between n and m times
| Creates an OR condition
^ Matches the start of a line
$ Matches the end of a line
\ Escapes metacharacters or forms part of other metacharacters like \n or \w

Question 1

Choose the regular expressions that match lines consisting only of “New” or “new” (select two).

Options:

  • ^[Nn]ew$
  • ^N|new$
  • ^[Nn][e][w]$
  • ^New|new$
  • ^[New][new]$

Answer:

  • ^[Nn]ew$
  • ^[Nn][e][w]$

Explanation:

  • ^N|new$ matches “N” as well.
  • ^New|new$ matches “Newnew” as well.
  • ^[New][new]$ matches “Nn” or “ee,” among others.

Question 2

Choose the regular expression that matches lines consisting only of one or more digits.

Options:

  • /^[0-9].$/
  • /^[0-9]*$/
  • /^[0-9][0-9]*$/
  • /^[0-9][0-9].*$/

Answer:

  • /^[0-9][0-9]*$/

Explanation:

  • /^[0-9].$/ matches a digit followed by any character, so “0a” would match.
  • /^[0-9]*$/ matches zero or more digits, so it also matches empty lines.
  • /^[0-9][0-9].*$/ matches two digits followed by any characters, so “00a” would match.

Question 3

What is the output of the following code?

p  "abc def 123 ghi 456".scan(/\d+/).length

Answer:

  • 2

Explanation:

  • The pattern matches sequences of digits. In the string, there are two such sequences: “123” and “456.”

Question 4

What is the output of the following code?

p "HogeHOGEhoge"[/[A-Z][^A-Z]+/]

Answer:

  • “Hoge”

Explanation:

  • The pattern matches a capital letter followed by one or more non-capital letters.

Reference

プロを目指す人のためのRuby入門[改訂2版] 言語仕様からテスト駆動開発・デバッグ技法まで

See Also