← Back to Upcase

Regular Expressions - Regular Expressions: Character Classes

(Upcase ) #1

This topic is for the Regular Expressions: Character Classes exercise in the Regular Expressions trail. Post any questions, corrections, or pointers you have to share with other Upcase subscribers.

(James Tomasino) #2

I’m having trouble understanding the failure of this regexp to match the string “J B”. It works in vim and in javascript. Is there something different syntactically in ruby that would be throwing this off, or is there a problem in the test?

def matching_first_name_last_name

As you can see on regexr, this solution seems to match the pattern correctly. My ruby knowledge is limited to coursera and codeacademy, though. I know different languages implement regular expressions in different ways, like JavaScripts lack of look behinds, or the special magic modes in Perl.

(Derek Prior) #3

How are you trying to match? The code you have show defines a method that returns a regular expression, but it does not test it against anything.

(Andy Waite) #4

The regexp itself seems fine. You can confirm this in irb:

irb(main):001:0> /^[A-Z].*\s[A-Z]/.match("J B")
=> #<MatchData "J B">
(Brian Lu) #5

the test expect not to match “J B”.

(Zhao Li) #6


The directions for the “two capitalized names” was a bit confusing:

# Returns a regex matching two capitalized names, separated by some amount of whitespace.
# Whitespace can be tabs (represented as \t in strings), spaces, newlines, etc.
# It should match:
#   * "Jesse \t James"
#   * "James        Bond"
#   * "7 Costanza"
# It should not match:
#   * "JamesBond"
#   * "james bond"

Should 7 Costanza really be matched if we are looking for 2 capitalized names?

Not sure if this is the correct place for this comment, but the character classes repo doesn’t seem to be on Github.


(Eric Bouchut) #7


I noticed a typo in this blog post, which is great by the way:

It seems to me

Let’s say we only wanted to look for numbers between 100 and 999.

should be instead

Let’s say we only wanted to look for numbers between 000 and 999.

See: http://rubular.com/r/VF1DsXoJna

(Chris Toomey) #8

Hi @ebouchut, you are certainly right from a regex standpoint. The pattern \d{3} does not require the first number to be 1 or greater. That said, I believe the wording of the post is referring to the fact that any number less than 100 would be written with only 2 digits, e.g. 25, not 025.

Just for completeness sake, if you wanted to to specifically match any number between 100 and 999, I would likely use \b[1-9]\d{2}\b as the pattern. \b for word boundaries, any of 1 through 9, then any 2 digits, then another word boundary. See http://rubular.com/r/VF1DsXoJna for pattern and sample test values.

(Eric Bouchut) #9

Hi @christoomey , you are right, I now understand why Britt used 100.
Thanks for the clear explanation and the tip about the word boundaries surrounding the 3 digits.